Express js req.body returns empty

后端 未结 2 1632
南笙
南笙 2021-01-18 23:57

I\'ve tried the all solutions from some another stackoverflow posts but it didn\'t solved my issue.

Here is my app.js

var express = requ         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 00:20

    After removing the last 4 lines of code (to be sure you are configuring correctly the routes) and adding this test lines:

    app.post('/ping', function (req,res) {
        console.log(req.body);
        res.send('ok ' + req.body.test);
    });
    let server = http.createServer(app);
    server.listen(8899, function onstart() {
        console.log('server listening');
    });
    

    When I run:

    curl -X POST http://localhost:8899/ping -d '{"test": 1234}'
    

    I get ok undefined, like you did. After adding the proper content-type header:

    curl -X POST http://localhost:8899/ping -d '{"test": 1234}' -H "content-type: application/json"
    

    it works like a charm and I get ok 1234. So I think you are missing the "content-type: application/json" header in your postman.

提交回复
热议问题