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...');
via Luis MartÃnez
No comments:
Post a Comment