Alejandro Flores
Alejandro Flores

Reputation: 95

Params empty on POST request

I am trying to make a POST request sending 2 params using HTTPClient for NodeJS.

var HTTPClient = require('httpclient')

var options = {
    hostname: 'localhost',
    path: '/',
    port: 8081,
    secure: false,
    method: 'POST',
    headers: {
      'x-powered-by': 'HTTPClient.js'
    },
    'Content-Type': 'application/x-www-form-urlencoded',
    params:{
        command:'TEST',
        param1:'TEST'
    }
} 

var example1 = new HTTPClient(options)
example1.post('/executeGraph1', function (err, res, body) {
    console.log(typeof body,body);
})

Then I am using Express to catch the POST request

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

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '')));

app.post('/executeGraph1', function (req, res) {
   console.log("Got a POST request for grahBar");

   console.log("params",req.params);
   console.log("body",req.body);
   console.log("query",req.query);
})

var server = app.listen(8081, function () {

   var host = server.address().address
   var port = server.address().port

   console.log("Example app listening at http://%s:%s", host, port)
})

I have tried solutions in other question like using 'Content-Type': 'application/x-www-form-urlencoded' Or app.use(bodyParser.urlencoded({extended: true})); but evrery time I keep getting empty variables. I have tried looking in properties body,params or query but all three options are empty arrays

Does anybody knows what is going wrong here?

Upvotes: 1

Views: 3307

Answers (1)

Kieper
Kieper

Reputation: 315

Your server code is alright, req.query will contain query parameters, but req.params is used when your route string is defined like that /executeGraph1/:paramName there might be more params prefixed with : for e.g /res1/:param1/res2/:param2/:param3.

Altough I have not been using httpclient module, adding query string in request url works, e.g

example1.post('/executeGraph1?queryParamName=value', function (err, res, body) {
    console.log(typeof body,body);
  })

Replacing params with query in your options variable also work.

I would suggest using https://github.com/request/request instead.

One last thing in your POST handler add as last line res.end() if you do not do this your request will hang and wait for timeout. end may take argument which will be sent to client.

Upvotes: 2

Related Questions