javascript - API 调用时获取无效 JSON

标签 javascript json api express

我正在尝试使用 GoToMeeting 的 API 并发出 POST 请求来创建 session 。目前,我只是尝试对 session 正文进行硬编码并发送 header ,但我收到了无效的 JSON 错误,并且不确定原因。这是该路线的代码:

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

当我访问该路由器时,出现以下错误:

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

如有任何建议,我们将不胜感激!

最佳答案

tl;博士

您正在为 JavaScript 对象表示的 body 传递 fetch 值。它通过(隐式)调用其 .toString() 方法将其转换为字符串。这不会给你 JSON。然后,您调用的 API 会提示并告诉您它不是 JSON。

您需要使用以下方法将对象转换为 JSON:

body: JSON.stringify(meetingBody), 
<小时/>

测试用例

这演示了问题和解决方案。

服务器

这是一个非常原始且不完整的 GoToMeeting API 模拟。它只是回显请求正文。

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!'))

客户端

这代表您的代码,但删除了 Express 服务器。仅保留与向 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));

运行测试用例的结果

服务器和客户端的日志显示:

[object Object] 

这就是调用 meetingBody.toString() 时得到的结果。

如果您按照本答案顶部的描述更改代码,您将得到:

{"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"}

这是 JSON,这是 API 所期望的。

<小时/>

旁白

MIME 类型中没有空格。 接受:'application/json',应为接受:'application/json',。不过,这可能不会给您带来任何问题。

关于javascript - API 调用时获取无效 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49411755/

相关文章:

json - 如何在 couchdb View 中调用另一个 View ?

python - 如何使用 python 请求调用 Twitter oEmbed API?

javascript - 按钮填充可用空间,将它们分组到下拉菜单中

json - AJAX 无法从 Perl 正确接收 JSON 编码数据

javascript - jQuery UI 自动完成与 json 文件

python - 使用 django-tastypie 创建、更新和删除调用

api - RESTful API 身份验证/安全

javascript - 减少大型 javascript 操作对客户端的明显滞后的方法

javascript - jquery 库的兼容性问题

javascript - 我想移动多个数组列表中的元素