curl,节点:将 JSON 数据发布到节点服务器

curl, node: posting JSON data to node server

我正在尝试测试我用 CURL 编写的小型节点服务器,但由于某种原因失败了。我的脚本如下所示:

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');  

当我将浏览器指向:

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

效果很好。我希望通过 JSON 发送一些数据,所以我添加了一个部分来查看我是否可以读取请求的正文部分('else' 块)。但是,当我在 Curl 中执行此操作时,我得到 'undefined':

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

我不确定为什么会失败。

问题是您将这两个请求视为 GET 请求。

在这个例子中,我为每个方法使用了不同的逻辑。考虑 req 对象充当 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');