Javascript客户端在POST请求中发送正文,但node.js服务器将其取消为空

时间:2017-05-12 10:55:17

标签: javascript node.js rest post

我希望能够看到{"内容":"测试数据"}(它应该作为POST请求的主体从客户端发送)我的服务器控制台,而不是我得到:

Listening to 8080...
I'm in myServer.use
POST request received
req.params: {}
req.body: undefined
req.query: {}

这是我的客户,它只是一个启动他的onclick功能的按钮:

<!DOCTYPE html>
<html>
    <head>
        <title>REST WebClient</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>This web is a REST client.</p>

    <script type="text/javascript">
    function POSTpressed(){
                //Making the request
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open( "POST", 'http://127.0.0.1:8080/v0/prueba/', true ); // false for synchronous request
                xmlHttp.send( {"content":"test data"} );
    }
    </script>

        <input type="button" onclick="POSTpressed();" id="POSTbutton" value="POST"/>

     </body>
</html>

这是服务器。如果有人试图重现它,则需要安装&#34; express&#34;库。

var express = require('express');
var myServer = express();

//stuff for server to going on
myServer.use(function(req, res, next){
    console.log("I'm in myServer.use");
    res.set('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Origin', '*'); //general access
    next();
});

//function which handles POST requests
myServer.post('/v0/prueba/', function(req, res){
    console.log('POST request received');
    //trying to see the sent body
    console.log("req.params: "+JSON.stringify(req.params));
    console.log("req.body: "+ req.body); //req.body.content would throw error: no content in undefined
    console.log("req.query: "+ JSON.stringify(req.query));

    res.send(null);

});//myServer.post

myServer.listen(8080);
console.log('Listening to 8080...');

3 个答案:

答案 0 :(得分:1)

在服务器端,您需要添加正文解析器中间件来解析正文:

var bodyParser = require('body-parser')

  :

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

答案 1 :(得分:0)

var bodyParser = require('body-parser'); 
myServer.use(bodyParser.json());
myServer.use(bodyParser.urlencoded({ extended: true }));

你需要使用身体解析器来获取身体。

答案 2 :(得分:0)

您需要使用body-parser来获取客户端发送的数据 见Body-parser