0

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.

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.