[英]Node JS send empty JSON body
我有下面的代碼,它應該發送一個 POST 請求,但有一個空的 JSON 主體:
request.post({
url: url,
headers: {
"data_digest": 'muZ7EcapQZVb77RF',
"partner_code": "ebfebc241db9b9c1a",
"msg_type": "GET_BASEDATA_TRANSPORT",
"msg_id": '1590464383047',
"Accept-Language": "zh-cn"
},
json: true,
body: {}
}, function(error, response, body) {
console.log(body);
});
然而,這不斷返回
'System Exception:\r\ntype org.springframework.web.HttpMediaTypeNotAcceptableException\r\nmessage:Could not find acceptable representation'
但是使用 Postman 我能夠正確發送具有完全相同標頭的 POST 請求,但在原始格式的 Body 參數中只有一個空的 {}。
如何在 Node JS 中發送帶有空 JSON 主體的 POST 請求?
你送屍體的方式很好。 如果您查看發送的實際請求(例如使用 Fiddler 或 Wireshark),您會看到正文已正確發送。 問題是其他問題 - 相反,您會看到標題並不完全相同。
Using json
(either with json: true
and body
, or as you do it, with json
as object) also automatically sets the Accept
header to application/json
and attempts to parse the response as JSON.
似乎此服務器chiguotest.ytoglobal.com
有一個錯誤,它返回 JSON 但不處理Accept
header 正確(我測試了它並且似乎正確地返回了服務器“ text/plain
pla) 所以request
(正確地)告訴服務器“我希望你返回 JSON”,但服務器說“什么,JSON?不,我不知道如何返回 JSON,只有文本,抱歉。”。 然而,它實際上確實返回了 JSON。
您可以通過顯式發送Accept: */*
header 來規避此服務器錯誤:
request.post({
url: url,
headers: {
"data_digest": 'muZ7EcapQZV',
"partner_code": "ebfebc241db9b9c",
"msg_type": "GET_BASEDATA_TRANSPORT",
"msg_id": '1590464383047',
"Accept-Language": "zh-cn",
"Accept": "*/*"
},
json: true,
body: {}
}, function(error, response, body) {
console.log(body);
});
我的 output:
{
"data": {
"productKinds": [
{
"productCnname": "(美國)測試用-不拉G單號",
"productCode": "1",
"productEnname": "1",
"productServerhawbcodeNeed": "Y"
},
{
"productCnname": "散客可見產品",
"productCode": "111",
"productEnname": "內部產品",
"productServerhawbcodeNeed": "N"
},
... many more entries ...
]
},
"errorCode": "SUCCESS",
"errorMsg": "成功",
"status": true
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.