const http = require('http');const hostname = '127.0.0.1';const port = 3000;const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n');});/** 注意,设置了 hostname 就只开放对应的hostname访问了哦 Linux 可以使用 netstat -ntpl检查端口开放情况Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1380/sshd tcp 0 0 127.0.0.1:3000 0.0.0.0:* LISTEN 1794/node tcp6 0 0 :::80 :::* LISTEN 3019/node tcp6 0 0 :::22 :::* LISTEN 1380/sshd */server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);});
const http = require('http');function addCookie(res, { name, value, expireHours }){ var cookieString=name+"="+escape(value); //判断是否设置过期时间 if(expireHours > 0){ var date = new Date(); date.setTime(date.getTime+expireHours*3600*1000); cookieString = cookieString+"; expire="+date.toGMTString(); } const cookies = res.getHeader('Set-Cookie'); cookies.push(cookieString); res.setHeader('Set-Cookie', cookies);}function getQuery(req) { const search = {}; (req.originalUrl.split('?').slice(1) || []).forEach(item => { const [key, value] = item.split('='); search[key] = value; }) console.log(search); return search;}const server = http.createServer((req, res) => { console.log(req instanceof http.IncomingMessage); // true res.setHeader('Content-Type', 'text/html'); res.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); const contentType = res.getHeader('content-type'); // 'text/html' console.log(contentType) addCookie(res, {name: "ljy998", value: "999", expireHours: 30}) const cookies = res.getHeader('set-cookie'); // ['type=ninja', 'language=javascript'] console.log(cookies) // Object console.log(typeof cookies) // 每次用户请求都会进入此方法。 // http://127.0.0.1:3000/index.html?abc=666 // /index.html?abc=666 GET undefined undefined undefined res.end(`${req.url} ${req.method} ${req.query} ${req.params} ${req.body}`);});server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');});server.listen(3000, function(){ console.log("web service start, port 3000")});
use 的实现demo
const http = require('http');function call(handle, route, err, req, res, next) { var arity = handle.length; var error = err; var hasError = Boolean(err); try { if (hasError && arity === 4) { // error-handling middleware handle(err, req, res, next); return; } else if (!hasError && arity < 4) { // request-handling middleware handle(req, res, next); return; } } catch (e) { // replace the error error = e; } // continue next(error); }const proto = {};proto.handle = function handle(req, res) { var index = 0; var stack = this.stack; function next(err) { var layer = stack[index++]; var route = layer.route; call(layer.handle, route, err, req, res, next); } next();}proto.use = function use(route, fn) { // 支持只传入一个fn var handle = fn; var path = route; // default route to '/' if (typeof route !== 'string') { // 支持只传入一个fn handle = route; path = '/'; } if (path[path.length - 1] === '/') { path = path.slice(0, -1); } this.stack.push({ route: path, handle: handle });}function createServer() { function app(req, res, next){ // 首次的时候没有next, next = undefined console.log(req.url) app.handle(req, res, next); } app.use = proto.use; app.handle = proto.handle; app.route = '/'; app.stack = []; return app;}const app = createServer()app.use(function(req, res, next) { res.__fn = function () { console.log("__fn") return 'hello world' } next()})app.use(function(req, res, next) { const result = res.__fn() res.end(result)})// http.createServer(fn) 中的 fn 所有的http请求都会进入这个方法const server = http.createServer(app)server.listen(3000, function(){ console.log("web service start, port 3000")});