Felipe Garrido
Felipe Garrido

Reputation: 25

Can't get the data from a post request in a node app behind a nginx reverse proxy

I have a node.js app behind a nginx reverse proxy and I can't get the data when I make a POST request (using a REST Easy addon for firefox). I look up in the site and I can't find something useful. Here is my code.

nodetest.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

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

app.post('/test', function (req, res){
  var p1 = req.body.param1;
  var p2 = req.body.param2;
  res.send('param1: '+p1+' param2: '+p2+' ');
});

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(8081, function () {
  console.log('Example app listening on port 8081!');
});

/etc/nginx/sites-available/default

server {
        listen 80;

        server_name funklipe.cl;

        location / {
                proxy_pass http://127.0.0.1:8081;
                proxy_redirect off;
                proxy_http_version 1.1;
                proxy_buffering off;
        }
}

I use pm2 for run the node app

pm2 start nodetest.js

when make the post request (with param1=foo and param2=var) I get

param1: undefined param2: undefined 

I hope you can help me, if you need more info just let me know

Thanks in advance

Upvotes: 1

Views: 1853

Answers (1)

Nehal J Wani
Nehal J Wani

Reputation: 16629

Your nginx config seems OK to me.

At your client side, make sure that you set the header properly. For example:

If you specify application/json:

$ curl -X POST -H 'Content-Type: application/json' -d '{"param1": "this_is_param1", "param2": "this_is_param2"}' http://localhost:8081/test
param1: this_is_param1 param2: this_is_param2

If you specify application/x-www-form-urlencoded:

$ curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' -d param1=this_is_param1 -d param2=this_is_param2 http://localhost:8081/test
param1: this_is_param1 param2: this_is_param2

But if you don't specify the header, then the client will use the default. And the behavior will be unexpected:

$ curl -X POST -d '{"param1": "this_is_param_1", "param2": "this_is_param2"}' http://localhost:8081/test
param1: undefined param2: undefined

Upvotes: 1

Related Questions