node.js处理POST请求

/*
 * @Description: post
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-31 13:42:53
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-31 13:53:29
 */

const http  =require("http");
const querystring = require("querystring");

const server = http.createServer((req,res)=>{
    if(req.method === 'POST'){
        let str ='';
        req.on('data',(chunk)=>{
            str+=chunk.toString();
        })
        req.on('end',()=>{
            res.writeHead(200,{
                'content-type' : 'application/json;charset=utf-8'
            })
             res.write(JSON.stringify(querystring.parse(str))); //postman下执行x-www-form-urlencoded application/x-www-form-urlencoded 传递到web服务端时
            //res.write(str); //postman下执行raw application/json 传递到web服务端时
            res.end()
        })
        console.log(req.headers['content-type']);
        
    }
    
})

server.listen(3000,()=>{
    console.log('local host:3000 Listen...');
})
/*
 * @Description: index
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-31 12:27:35
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-31 12:58:50
 */
const http  =require("http");
const querystring = require("querystring");

const server = http.createServer((req,res)=>{
    let str ='';
    req.on('data',(chunk)=>{
        str+=chunk;
    })
    req.on('end',()=>{
        res.writeHead(200,{
            'content-type' : 'application/json;charset=utf-8'
        })
        res.write(JSON.stringify(querystring.parse(str)));
        res.end()
    })
})

server.listen(3000,()=>{
    console.log('local host:3000 Listen...');
})

 

posted @ 2021-10-31 13:59  南柯Dream丶  阅读(148)  评论(0)    收藏  举报