2016-04-11 14 views
0

In meinem NodeJS Code erhalten, verwende ich http Modul HTTP-Anforderung und Antwort auf Benutzer zu erhalten. Ich will request Körper nehmen, die ich eine JSON erwarten.NodeJS - Anfrage Körper wie PHP file_get_contents

von this link Bezug I gelten wie folgt zu meinem Code:

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) 
}) 

Ich habe versucht, den Code oben zu testen im Terminal folgenden Befehl ein:

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

Aber die Antwort ist nicht das, was ich erwarten()! Stattdessen ist es ein Code-Snippet, von dem ich nicht weiß, wo es herkommt. Siehe unten:

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

Können Sie mir das Problem in meinem Code zeigen? Und warum ist der Code-Snippet oben statt {"MyKey":"My Value"} zurückgekehrt?

Vielen Dank.

Edit1:

ich im Terminal ein detaillierteres Befehl nur versucht, aber noch kein Glück.

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

Antwort

0

Ich finde nur das Problem, unter: var content = Buffer.concat(body).toString !! Es muss var content = Buffer.concat(body).toString() sein! Ich vermisste wichtigsten Teil ().

Danke, jeder

Verwandte Themen