最原生Web Server
const http = require('http');const server = http.createServer((req, res) => {const url = req.url,method = req.method;if(url === '/'){req.setHeader('Content-Type', 'text/html');res.write('<html>');res.write('<header><title>请输入你的内容</title></header>');res.write('<body><form action="/message" method="POST"><input type="text" name="message" /><button="submit">发送</button></form></body>');res.write('</html>');return res.end();}if(url === '/message' && method === 'POST'){const body = [];req.on('data', (chunk) => {body.push(chunk);});req.on('end', () => {const parsedBody = Buffer.concat(body).toString(),message = parsedBody.split('=')[1];fs.writeFileSync('msg.txt', message);});res.statusCode = 302;res.setHeader('Location', '/');return res.end();}req.setHeader('Content-Type', 'text/html');res.write('<html>');res.write('<header><title>我的页面</title></header>');res.write('<body><h1>你好, NodeJS!</h1></body>');res.write('</html>');res.end();});server.listen(3000);
- req.url
- req.method
- req.headers
