curl + HTTP Server Nodejs

1

Good morning!

I created an HTTP server using nodeJS as follows:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));
app.post('/', function(request, response, next) {
    console.log('body', request.body); // vai chegar aqui o  {"password":1138}
    console.log(request.body.password); // 1138
   response.send('OK!!');
});

Then I used the following command in the terminal:

curl -X POST http://localhost:3000 -H 'Content-Type: application/json' -d '{"password":1138}'

The issue is that the line console.log('body', request.body); returned right content JSON body { '\'{password:1138}\'': '' } , but line console.log(request.body.password); returned undefined .

I did not get any error, the issue was that request.body.password returned undefined.

I even changed the section

app.use(bodyParser.urlencoded({
    extended: true
}));

by

app.use(bodyParser());

And although the message appeared:

  

body-parser deprecated bodyParser: use individual json / urlencoded middlewares
  body-parser deprecated undefined extended: provide extended option node-modules \ body-parser \ index.js

No error, but again request.body.password is undefined

Does anyone know what might be happening?

    
asked by anonymous 21.08.2016 / 15:26

1 answer

1

I solved it!

The problem was in the way that the header was being passed in the curl. Debugging I saw that the header in Node.js was not like JSON being that I had passed in the curl.

In the cURL command I added -i before -H :

curl -X POST localhost:3000 -i -H 'Content-Type: application/json' -d '{"password":1138}' 

The result appeared right in console.log(request.body); and console.log(request.body.password);

Thanks for the help!

    
22.08.2016 / 18:05