编程语言
首页 > 编程语言> > node.js处理http请求总结

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,responseData,const,url,res,req,js,http,method
来源: https://www.cnblogs.com/NanKe-Studying/p/15489408.html