【问题标题】:Problems to use GitHub api in backend with Axios在 Axios 的后端使用 GitHub api 的问题
【发布时间】:2020-02-20 19:22:44
【问题描述】:

我正在尝试在我的 express 应用程序中使用 github 的 api,但它不起作用。 当我将 return 与 res.json(console.log(users)) 一起使用时,我会根据需要接收所有用户,但是当我使用 return res.json(users);有时我收到错误 500,现在出现此错误:

Converting circular structure to JSON",
    "name": "TypeError"

我不知道为什么,因为这是一个简单的应用程序.. 这是我的 axios 配置:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.github.com',
});

export default api;

这是我的方法代码:

class UserController {
  async show(req, res) {
    const { username } = req.query;

    if (!username) {
      return res.status(400).json({ error: 'Invalid user' });
    }
    const user = await api.get(`/users/${username}`);

    return res.json(user);
  }

  async index(req, res) {
    const { page = 1 } = req.query;
    const users = await api.get(`users?since=${page}`);
    return res.json(users);
  }
}

export default new UserController();

【问题讨论】:

    标签: node.js express axios


    【解决方案1】:

    axios 返回类似如下的响应对象:

    data: {...}
    status: 200
    statusText: ""
    headers: {..}
    config: {...}
    request: {...}
    

    理想情况下,我认为您想返回response.data。所以试试

    const response = await api.get(`/users/${username}`);
    res.json(response.data);
    

    【讨论】:

      【解决方案2】:

      您需要从 axios 响应中获取 data 属性,不是吗?

      const user = await api.get(`/users/${username}`);
      
      return res.json(user.data);
      

      请看这里:https://github.com/axios/axios#response-schema

      request 字段是一个循环结构,因此发送整个响应对象会导致该错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2018-08-09
        • 2022-06-30
        • 2020-12-04
        • 2021-05-29
        • 2019-01-05
        • 2014-08-27
        相关资源
        最近更新 更多