node.js处理http请求总结

2021/10/31 14:39:46

本文主要是介绍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请求总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程