简体   繁体   中英

Javascript client sends body in POST request, but node.js server gets it empty

I would like to be able to see {"content":"test data"} (it is supposed to be sent from the client as the body of the POST request) in my server console, instead I get:

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

Here is my client, it's just a button which launches his onclick function:

<!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>

Here is the server. If anybody tries to reproduce it, will need to install the "express" library.

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...');

On server side, you need to add body-parser middleware for parsing the body:

var bodyParser = require('body-parser')

  :

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

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

You need use body-parser to get the body.

您需要body-parser来获取客户端发送的数据,请参见Body-parser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM