在将json-server api与axios集成时,我有一个奇怪的行为。
我使用json-server来提供db.json文件
json-server --watch db.json --port 4000
在我的react应用程序中,我使用axios调用"http://localhost:4000/tasks“
在postman上进行测试,该API返回结果,并且工作正常。
但是使用下面的代码片段(axios),它将react应用程序的两个域和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
并因此抛出not found - 404异常
你知道为什么会发生这种事吗?
奇怪的是,当我使用另一个像“星球大战”API "https://swapi.co/api/people/1“这样的api时,它就像一个魔咒。
先谢谢你...
发布于 2018-12-18 08:59:10
我已经通过使用环境变量修复了这个问题。
我刚刚创建了一个".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');
}
而且它工作得很完美。
https://stackoverflow.com/questions/53812984
复制相似问题