0
私のnodejsコードでは、http
モジュールを使用してHTTPリクエストとユーザーへの応答を取得します。私はrequest
体を取って、私はJSONを期待しています。 this linkから参照nodejs - phpのfile_get_contentsのようなリクエストボディを取得
は、私は次のように私のコードに適用されます。
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