Node.js开发博客项目-http请求处理(1)
处理get与post请求示例代码:
const http = require(‘http‘); const querystring = require(‘querystring‘); const server = http.createServer((req,res) => { const method = req.method; const url = req.url; const path = url.split(‘?‘)[0]; const query = querystring.parse(url.split(‘?‘)[1]); // 设置返回格式为json res.setHeader(‘Content-type‘,‘application/json‘); // 返回的数据 const resData = { method, url, path, query } if(method === ‘GET‘) { res.end(JSON.stringify(resData)); } if(method === ‘POST‘) { let postData = ‘‘; req.on(‘data‘,chunk => { postData += chunk.toString(); }) req.on(‘end‘, () => { resData.postData = postData; res.end(JSON.stringify(resData)); }) } }) server.listen(8000,() => { console.log(‘listening on 8000 port‘); }) console.log(‘ok‘);
Node.js开发博客项目-http请求处理(1)
原文:https://www.cnblogs.com/moqiutao/p/15220880.html