![](/img/trans.png)
[英]Sending a POST request with JSON from Android to a node.js server
[英]Natively access JSON POST payload from Node.js server
考慮以下對Node.js服務器的HTTP POST
調用:
curl -H "Content-Type: application/json" \
-X POST \
-d '{"jsonKey":"jsonValue"}' \
'http://localhost:8080?abcd=efgh'
我想訪問URL參數和POST請求的JSON有效負載。
通過導入url.parse
訪問URL參數非常簡單:
var server = http.createServer(function(req, res) {
// Parse the params - prints "{ abcd: 'efgh' }"
var URLParams = url.parse(req.url, true).query;
console.log(URLParams);
// How do I access the JSON payload as an object?
}
但是,如何使用本機Node.js庫(沒有任何npm
導入)訪問JSON有效負載?
我嘗試了什么
req
到console.log
,但沒有找到POST對象 req
的文檔,該文檔的類型為http.IncomingMessage
從文檔:
當接收到POST或PUT請求時,請求主體對於您的應用程序可能很重要。 獲取主體數據比訪問請求標頭要復雜得多。 傳遞給處理程序的請求對象實現ReadableStream接口。 就像其他任何流一樣,可以在其他地方收聽或通過管道傳輸此流。 通過偵聽流的“數據”和“結束”事件,我們可以從流中直接獲取數據。
https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var server = http.createServer(function(req, res) {
// Parse the params - prints "{ abcd: 'efgh' }"
var URLParams = url.parse(req.url, true).query;
console.log(URLParams);
// How do I access the JSON payload as an object?
var body = [];
req.on('data', function(chunk) {
body.push(chunk);
}).on('end', function() {
body = Buffer.concat(body).toString();
if (body) console.log(JSON.parse(body));
res.end('It Works!!');
});
});
req
是一個流,因此如何訪問它取決於您要如何使用它。 如果只想將其獲取為文本並將其解析為JSON,則可以執行以下操作:
let data = "";
req.on("readable", text => data += text);
req.on("end", () => {
try {
const json = JSON.parse(data);
}
catch (err) {
console.error("request body was not JSON");
}
/* now you can do something with JSON */
});
只是作為補充; 如果您想從POST主體創建對象,則使用以下代碼:
const body2Obj = chunk => {
let body = {};
let string = chunk.toString();
if (!string.trim()) return body;
string.split('&').forEach(param => {
let elements = param.split('=');
body[elements[0]] = elements[1];
});
return body;
};
然后使用上面的stdob--所解釋的:
var body = [];
req.on('data', chunk => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body);
body = body2Obj(body);
// ...
});
我更喜歡這種解決方案,而不是使用超大的第三方模塊來僅解析請求的主體(有時,出於某些原因,人們建議這樣做)。 可能是我的版本較短。 當然,這僅適用於url編碼的格式化主體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.