【问题标题】:React Axios Appends Window Origin To Provided Url (json-server)React Axios 将窗口来源附加到提供的 Url (json-server)
【发布时间】:2019-05-17 16:30:26
【问题描述】:

在将 json-server api 与 axios 集成时,我有一个奇怪的行为。

我使用 json-server 来提供一个 db.json 文件

json-server --watch db.json --port 4000

在我的反应应用程序中,我使用 axios 调用“http://localhost:4000/tasks

在postman上测试,API返回结果,运行正常。

但是使用下面的代码 sn-p (axios) 它将反应应用程序的域和 api Url 连接到请求。

try {
        return axios({
            method: 'GET',
            url: `http://localhost:4000/tasks`
        }).then((response) => {
            debugger;
            return response;
        });
    } catch (error) {
        return new Error('Failed to retrieve Tasks');
    }

我在浏览器网络中检查,然后我像这样的请求 URL

请求网址:http://localhost:3000/http//localhost:4000/tasks

因此抛出未找到的 404 异常

知道为什么会这样吗?

奇怪的是,当我使用另一个 API,如星球大战 api“https://swapi.co/api/people/1”时,它就像一个魅力。

提前谢谢...

【问题讨论】:

  • 您好,如果您有代理字段,请检查您的 package.json。如果是,请将您的代理更改为 localhost:4000 并调用 get url,如下所示:'/tasks'。或者:删除代理,你的第一个代码就可以了
  • 我没有代理字段

标签: reactjs axios json-server


【解决方案1】:

我已经通过使用环境变量解决了这个问题。

我刚刚创建了一个“.env.development”文件并添加了“REACT_APP_API_BASEURL = 'http://localhost:4000'”。

然后我使用如下:

try {
    return axios({
        method: 'GET',
        url: `${process.env.REACT_APP_API_BASEURL}/tasks`
    }).then((response) => {
        debugger;
        return response;
    });
} catch (error) {
    return new Error('Failed to retrieve Tasks');
}

而且效果很好。

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2020-01-09
    • 2013-07-24
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多