繁体   English   中英

节点 JS 发送空的 JSON 主体

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM