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