一、创建简易Server
const http = require('http');
const URL = require('url');const HTTP_PORT = 8088;const server = http.createServer((req, res) => {const { headers, method, url } = req;console.log( headers, method, url);
});server.listen(HTTP_PORT, () => {console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})
二、url相关处理
const http = require('http');
const URL = require('url');const HTTP_PORT = 8088;const server = http.createServer((req, res) => {const { headers, method, url } = req;console.log( headers, method, url);if(url === '/login'){res.end('hello outman');}else if(url === '/products'){res.end('products list');}else{res.end('error request');}const parseInfo = URL.parse(req.url);console.log(parseInfo);const { pathname, query } = URL.parse(req.url);const queryObj = URL.parse(query);console.log(pathname, queryObj);
});server.listen(HTTP_PORT, () => {console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})
三、请求配置与监听
const http = require('http');
const URL = require('url');const HTTP_PORT = 8088;const server = http.createServer((req, res) => {const { headers, method, url } = req;console.log( headers, method, url);req.setEncoding('utf-8');req.on('data', (data) => {console.log('data', data);const { username, password } = JSON.parse(data);console.log(username, password);});req.on('end', () => {console.log('传输结束');});res.end('outman msg')
});server.listen(HTTP_PORT, () => {console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})
四、常用HTTP CODE
HTTP状态码 | 状态描述 | 信息说明 |
---|
200 | OK | 请求成功 |
201 | Created | POST请求,创建新的资源 |
301 | Moved Pemanently | 请求资源的URL已经修改,响应中会给出新的URL |
400 | Bad Request | 客户端的错误,服务器无法或者不进行处理 |
401 | Unauthorized | 未授权的错误,必须携带请求的身份信息 |
403 | Forbidden | 客户端没有权限访问,被拒接 |
404 | Not Found | 服务器找不到请求的资源 |
500 | Internal Server Error | 服务器遇到了不知道如何处理的情况 |
503 | Service Unavailable | 服务器不可用,可能处理维护或者重载状态,暂时无法访问 |