PUT API请求返回JSON主体错误

时间:2020-05-16 21:03:40

标签: node.js json api put

我试图通过发送放置请求来更新通讯组列表,当我运行此代码并通过给它提供JSON正文在邮递员中对其进行测试时,我在node.js终端中收到此错误,声明为SyntaxError: Unexpected end of JSON input。知道我应该改变什么吗?

我的PUT API请求

 app.put("/api/Dls/Add/:groupId" , (req, res) => {
    const response = {
      success: false
    };
    if (Authorized.myToken) {
      response.success = true;
      response.data = {};
      var options = {
        method: 'PUT',
        url: 'https://SomeAPI.com/' + req.params.groupId,
        headers:
        {
          Accept: 'application/json',
          Authorization: 'Bearer' + ' ' + Authorized.myToken
        },

        body: JSON.stringify(req.body)

      };
      request(options, function (error, response, body){
        if (error) {
          console.log(error);
          return;
        }
        const data = response.body;
        const dls = JSON.parse(data)
        return res.json(dls);

      });
    }
 }); 

我正在通过邮递员传递的JSON正文以测试API调用

{
        "groupId": "123456789",
        "SomeField1": null,
        "SomeField2": "xxxxxxxxx",
        "SomeField3": true,
        "SomeField4": "xxxxxxxxx",
        "SomeField5": "xxxxxxxxx",
        "SomeField6": [
            "xxxxxxxxx"
        ],
        "SomeField7": "xxxxxxxxx",
        "SomeField8": "xxxxxxxxx",
        "SomeField9": "xxxxxxxxx",
        "SomeField10": "xxxxxxxxx",
        "SomeField11": [],
        "SomeField12": "xxxxxxxxx",
        "SomeField13": null,
        "SomeField14": false,
        "SomeField15": ["xxxxxxxxx"]
}

任何反馈表示赞赏!

2 个答案:

答案 0 :(得分:0)

如果您在此处发布的JSON是您通过邮递员传递的真实JSON,则它不是有效的JSON,因为您具有相同的名称属性。当我说有效时,表示发布到端点后会得到类似的内容。

{
  "groupId": "123456789",
  "SomeField": [
    "xxxxxxxxx"
  ]
}

请求npm软件包也已弃用,因此最好不要使用它,而应将其替换为Axios之类的东西。 TBH我没有在代码中看到任何导致您提到的错误的错误,您是否可以访问API来检查日志?在https://SomeAPI.com/端点上可能出了点问题。

答案 1 :(得分:0)

我弄清楚了问题所在,我需要在返回语句中添加.end

例如return res.status(200).end()