简体   繁体   中英

Node JS send empty JSON body

I have the code below which is supposed to send a POST request but with an empty JSON body:

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);
});

However this keeps returning

'System Exception:\r\ntype org.springframework.web.HttpMediaTypeNotAcceptableException\r\nmessage:Could not find acceptable representation'

But using Postman I'm able to correctly send POST request with the exact same headers but just an empty {} in the Body parameter with Raw format.

How can I send a POST request with an empty JSON body in Node JS?

Your way of sending the body is fine. If you'd look at the actual request sent (for example using Fiddler or Wireshark) you'd see the body is sent correctly. The problem is something else - instead you'd see that the headers are not the exact same.

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.

It seems that this server chiguotest.ytoglobal.com has a bug, where it returns JSON but does not handle the Accept header correctly (I tested it and it seems the server "thinks" it is returning text/plain ). So request is (correctly) telling the server "I expect you to return JSON", but the server says "What, JSON? No I don't know how to return JSON, only text, sorry.". Yet, it in fact does return JSON.

You can circumvent this server bug by explicitely sending an 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);
});

My 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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