d512
d512

Reputation: 34273

node.js http POST not working

I am having trouble getting my node.js server to do an http POST request to another node.js server. I am fairly certain that the problem lies with the http library or how I am using it because I can write a small HTML page that performs the POST exactly as I want.

Here is how the server receiving the POST is set up

var server = restify.createServer({
   name: 'some server',
   version: "1.0.0"
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.bodyParser());    
server.post('/theurl/', handler.handlePost);

server.listen(config.port, function() {
   console.log("starting server on port %d", server.address().port);
});

Inside the handlePost method I am doing this:

exports.handlePost = function(req, res, next) {
   console.log("body: %s", JSON.stringify(req.body));
   console.log("params: %s", JSON.stringify(req.params));
}

Here is the how the server that is sending the POST is doing it (this was taken directly from the node.js http docs)

var options = {
   host: '127.0.0.1',
   port: 8090,
   path: '/theurl/',
   method: 'POST'
};

var req = http.request(options, function(res) {
   ses.setEncoding('utf8');
   res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
   });
});

req.on('error', function(e) {
   console.log('problem with request: ' + e.message);
});

req.write("<some>xml</some>");
req.end();

When I run the POST, both req.body and req.params are undefined inside the handlePost method.

But if I put the following HTML in a browser, I can post to the service just fine.

<html>
   <head>
     <script>
       function doPost()
       {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.open("POST","http://localhost:8090/theurl/",false);
         xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
         xmlhttp.send("<some>xml</some>");
       }
     </script>
   </head>
   <body>
      <button type="button" onclick="doPost()">POST data</button>   
   </body>
</html>

So am I doing something wrong with the node.js http library?

Upvotes: 0

Views: 9932

Answers (3)

Shehroz Ayaz
Shehroz Ayaz

Reputation: 41

Make sure that you have added these things in your app.js file:

var bodyParser = require('body-parser'); // npm i body-parser

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

Upvotes: -1

AmirtharajCVijay
AmirtharajCVijay

Reputation: 1108

use the code below

var querystring = require('querystring');

    var data = querystring.stringify({
          username: yourUsernameValue,
          password: yourPasswordValue
        });

    var options = {
        host: 'my.url',
        port: 80,
        path: '/login',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': data.length
        }
    };

    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log("body: " + chunk);
        });
    });

    req.write(data);
    req.end();

Upvotes: 0

d512
d512

Reputation: 34273

Well, right after I posted this I realized that one thing I was doing in the HTML version that I wasn't doing in the node.js version was setting the Content-Type on the request. If I change the options to this, it works:

var options = {
   host: '127.0.0.1',
   port: 8090,
   path: '/theurl/',
   method: 'POST',
   headers: { "Content-type": "application/x-www-form-urlencoded" }
};

Upvotes: 2

Related Questions