简体   繁体   English

在API调用中获取无效的JSON

[英]Getting invalid JSON on API call

I'm trying to use GoToMeeting's API and making a POST request to create a meeting. 我正在尝试使用GoToMeeting的API,并发出POST请求来创建会议。 At the moment, I'm just trying to hardcode the body of the meeting and send headers but I'm receiving and I'm invalid JSON error and not sure why. 目前,我只是在尝试对会议正文进行硬编码并发送标题,但是我正在接收并且我是无效的JSON错误,并且不确定原因。 Here's the code for that route: 这是该路线的代码:

app.post('/new-meeting', (req, res) => {

  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application / json',
    Authorization: 'OAuth oauth_token=' + originalToken
  };

  console.log('-----------------------------------------------------------')
  console.log('Acess Token:');
  console.log('OAuth oauth_token=' + originalToken);
  console.log('-----------------------------------------------------------')

  const meetingBody = {
    subject: 'string',
    starttime: '2018-03-20T08:15:30-05:00',
    endtime: '2018-03-20T09:15:30-05:00',
    passwordrequired: true,
    conferencecallinfo: 'string',
    timezonekey: 'string',
    meetingtype: 'immediate'
  };

  return fetch('https://api.getgo.com/G2M/rest/meetings', {
    method: 'POST',
    body: meetingBody,
    headers: headers
  }).then(response => {

    console.log('response:');
    console.log(response);


    response
      .json()
      .then(json => {
        res.send(json);
        console.log(req.headers);
      })
      .catch(err => {
        console.log(err);
      });
  });
});

When I hit that router, I get the following error: 当我打那个路由器时,出现以下错误:

{
  "error": {
    "resource": "/rest/meetings",
    "message": "invalid json"
  }
}

Any advice would be appreciated! 任何意见,将不胜感激!

tl;dr tl; dr

You are passing fetch a value for the body represented by a JavaScript object. 您正在传递fetch由JavaScript对象表示的body的值。 It is converting it to a string by (implicitly) calling its .toString() method. 它通过(隐式)调用其.toString()方法将其转换为字符串。 This doesn't give you JSON. 这不会给您JSON。 The API you are calling then complains and tells you that it isn't JSON. 然后,您正在调用的API会抱怨并告诉您它不是JSON。

You need to convert your object to JSON using: 您需要使用以下方法将对象转换为JSON:

body: JSON.stringify(meetingBody), 

Test case 测试用例

This demonstrates the problem and the solution. 这说明了问题和解决方案。

Server 服务器

This is designed to be a very primitive and incomplete mock of GoToMeeting's API. 这被设计为GoToMeeting API的非常原始且不完整的模拟。 It just echos back the request body. 它只是回显请求主体。

const express = require("express");
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.text({ type: "*/*" }));

app.post("/", (req, res) => {
    console.log(req.body);
    res.send(req.body)
});

app.listen(7070, () => console.log('Example app listening on port 7070!'))

Client 客户

This represents your code, but with the Express server stripped out. 这代表了您的代码,但是Express服务器被剥离了。 Only the code relevant for sending the request to GoToMeeting's API is preserved. 仅保留与将请求发送到GoToMeeting的API相关的代码。

const url = "http://localhost:7070/";
const fetch = require("node-fetch");

const headers = {
    'Content-Type': 'application/json',
    Accept: 'application / json',
    Authorization: 'OAuth oauth_token=foobarbaz'
};

const meetingBody = {
    subject: 'string',
    starttime: '2018-03-20T08:15:30-05:00',
    endtime: '2018-03-20T09:15:30-05:00',
    passwordrequired: true,
    conferencecallinfo: 'string',
    timezonekey: 'string',
    meetingtype: 'immediate'
};


fetch(url, {
        method: 'POST',
        body: meetingBody,
        headers: headers
    })
    .then(res => res.text())
    .then(body => console.log(body));

Results of running the test case 运行测试用例的结果

The logs of both server and client show: 服务器和客户端的日志均显示:

[object Object] 

This is what you get when you call meetingBody.toString() . 这是您在调用meetingBody.toString()时得到的。

If you change the code as described at the top of this answer, you get: 如果按照此答案顶部所述更改代码,则会得到:

{"subject":"string","starttime":"2018-03-20T08:15:30-05:00","endtime":"2018-03-20T09:15:30-05:00","passwordrequired":true,"conferencecallinfo":"string","timezonekey":"string","meetingtype":"immediate"}

This is JSON, which is what the API is expecting. 这是JSON,这是API所期望的。


Aside 在旁边

MIME types do not have spaces in them. MIME类型中没有空格。 Accept: 'application / json', should be Accept: 'application/json', . Accept: 'application / json',应为Accept: 'application/json', This probably isn't causing you any problems though. 不过,这可能不会给您带来任何问题。

I believe the header is incorrect. 我相信标题不正确。

You need 'Accept: application/json' without space. 您需要不带空格的“ Accept:application / json”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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