2016-04-11 46 views
0

在我的nodejs代码中,我使用http模块来获取HTTP请求和对用户的响应。我想采取request正文,我期望一个JSON。nodejs - 获取php的请求体file_get_contents

this link参考,我申请到我的代码如下:

var http = require("http") 
var server = http.createServer(function(request, response) { 

    console.log("method: " + request.method) 
    console.log("url: " + request.url) 
    console.log("headers: " + request.headers) 

    var body = [] 

    request.on("error", function(error) { 

     console.log("Incoming request error: " + error) 

    }).on("data", function(chunk) { 

     body.push(chunk) 

    }).on("end", function() { 

     var content = Buffer.concat(body).toString 

     console.log("request body: " + content) 
     response.end("IP: " + request.connection.remoteAddress + "<br>" + content) 

    }) 

}).listen(PORT, function() { 
    console.log((new Date()) + " Server is listening on port " + PORT) 
}) 

我试图在终端下面的命令来测试上面的代码:

curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://myserverdomain.com:PORT 

但反应不是我期待({"MyKey":"My Value"})!相反,它是一个代码片断,我不知道它来自哪里。请看下图:

IP: <MY_IP_ADDRESS><br>function (encoding, start, end) { 
    encoding = String(encoding || 'utf8').toLowerCase(); 

    if (typeof start !== 'number' || start < 0) { 
    start = 0; 
    } else if (start > this.length) { 
    start = this.length; 
    } 

    if (typeof end !== 'number' || end > this.length) { 
    end = this.length; 
    } else if (end < 0) { 
    end = 0; 
    } 

    start = start + this.offset; 
    end = end + this.offset; 

    switch (encoding) { 
    case 'hex': 
     return this.parent.hexSlice(start, end); 

    case 'utf8': 
    case 'utf-8': 
     return this.parent.utf8Slice(start, end); 

    case 'ascii': 
     return this.parent.asciiSlice(start, end); 

    case 'binary': 
     return this.parent.binarySlice(start, end); 

    case 'base64': 
     return this.parent.base64Slice(start, end); 

    case 'ucs2': 
    case 'ucs-2': 
    case 'utf16le': 
    case 'utf-16le': 
     return this.parent.ucs2Slice(start, end); 

    default: 
     throw new TypeError('Unknown encoding: ' + encoding); 
    } 
} 

你能告诉我在我的代码的问题?为什么上面的代码片段返回而不是{"MyKey":"My Value"}

非常感谢。

EDIT1:

我只是尝试在终端更详细的命令,但仍然没有运气。

curl -H "Content-Type: application/json" -X POST -d '{"My key":"My value"}' http://myserverdomain.com:PORT 

回答

0

我只是找出问题所在:var content = Buffer.concat(body).toString !!它必须是var content = Buffer.concat(body).toString()!我错过了最重要的部分()

谢谢,大家