0

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

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

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

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

在邮递员上测试它,API返回结果并且工作正常。

但是使用下面的代码片段(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');
    }

我检查了浏览器网络,然后我像这样的请求网址

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

因此抛出一个未找到 - 404 异常

知道为什么会这样吗?

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

提前致谢...

4

1 回答 1

0

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

我刚刚创建了一个“.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');
}

它工作得很好。

于 2018-12-18T08:59:09.900 回答