node.js处理http请求总结

/*
 * @Description: get和post总结
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-31 14:02:45
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-31 14:16:35
 */
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]);

    res.setHeader('Content-Type', 'application/json');
    const responseData = {
        method,
        url,
        path,
        query
    }
    if (method === 'GET') {
        res.end(
            JSON.stringify(responseData)
        )
    }

    if (method === 'POST') {
        let postData = '';
        req.on('data', (chunk) => {
            postData += chunk.toString();
        })
        req.on('end', () => {
            responseData.postData = postData;
            res.write(JSON.stringify(responseData));
            res.end()
        })
    }

})

server.listen(3000, () => {
    console.log("localhost:3000 Listen...")
})

node.js处理http请求总结

 

node.js处理http请求总结

 

上一篇:ASP.NET - 自定义控件处理页面事件(控件与页面数据交互)的方法


下一篇:用Notepad++写python的小配置