【问题标题】:axios.get() returns undefined responseaxios.get() 返回未定义的响应
【发布时间】:2018-12-20 01:35:09
【问题描述】:

我在 aurelia 项目中使用 axios 并遵循他们的文档,我已经设置了一个基本的获取请求,如下所示

import Axios from '../../node_modules/axios/index';

export class testService {
  constructor() {
    this.axios = new Axios({
      withCredentials: false,
      headers:{
        "Accept": "application/json"
      },
      baseURL: 'http://localhost:3000/'
    });
  }

  test() {
    this.axios.get('/items')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
      });
  }
}

我有一个在“http://localhost:3000/items”上运行的 api 服务器,并在 Chrome 和 Postman 中点击该 url,我可以获得有效的 JSON 响应。但是,运行上面的代码(即调用test() 方法),记录的响应是undefined

我查看了类似问题的其他答案,但到目前为止,没有一个对我有用。我在这里做错了什么?

【问题讨论】:

    标签: ajax rest xmlhttprequest axios aurelia


    【解决方案1】:

    new Axios({ ...config ... }) 签名似乎有误。根据their doc,创建axios实例需要.create方法:

    this.axios = Axios.create({
      withCredentials: false,
      headers:{
        "Accept": "application/json"
      },
      baseURL: 'http://localhost:3000/'
    });
    

    【讨论】:

    • 谢谢,成功了。我确实看过their docs,但似乎他们只进一步解释了create 部分。
    • 顺便说一句,你可以用import Axios from 'axios'; 代替import Axios from '../../node_modules/axios/index';
    • 是的,这只是 VS 代码的自动填充功能。谢谢。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多