easythrees
easythrees

Reputation: 1660

curl, node: posting JSON data to node server

I'm trying to test a small node server I've written with CURL and for some reason this fails. My script looks like this:

http.createServer(function (req, res)
{
    "use strict";

    res.writeHead(200, { 'Content-Type': 'text/plain' });

    var queryObject = url.parse(req.url, true).query;

    if (queryObject) {
        if (queryObject.launch === "yes") {
            launch();
        else {
            // what came through?
            console.log(req.body);
        }
    }
}).listen(getPort(), '0.0.0.0');  

When I point my browser to:

http://localhost:3000/foo.js?launch=yes

that works fine. My hope is to send some data via JSON so I added a section to see if I could read the body part of the request (the 'else' block). However, when I do this in Curl, I get 'undefined':

curl.exe -i -X POST -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/foo.js?moo=yes

I'm not sure why this fails.

Upvotes: 0

Views: 932

Answers (1)

Gus Ortiz
Gus Ortiz

Reputation: 662

The problem is that you are treating both requests as if they where GET requests.

In this example I use a different logic for each method. Consider that the req object acts as a ReadStream.

var http = require('http'),
    url  = require('url');

http.createServer(function (req, res) {
    "use strict";

    if (req.method == 'POST') {
        console.log("POST");
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log("Partial body: " + body);
        });
        req.on('end', function () {
            console.log("Body: " + body);
        });
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('post received');
    } else {
        var queryObject = url.parse(req.url, true).query;
        console.log("GET");
        res.writeHead(200, {'Content-Type': 'text/plain'});
        if (queryObject.launch === "yes") {
            res.end("LAUNCHED");
        } else {
            res.end("NOT LAUNCHED");
        }
    }
    res.writeHead(200, { 'Content-Type': 'text/plain' });



}).listen(3000, '0.0.0.0');

Upvotes: 1

Related Questions