首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >React Axios将窗口原点附加到提供的Url (json-server)

React Axios将窗口原点附加到提供的Url (json-server)
EN

Stack Overflow用户
提问于 2018-12-17 18:11:41
回答 1查看 571关注 0票数 0

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

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

代码语言:javascript
代码运行次数:0
运行
复制
json-server --watch db.json --port 4000

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

在postman上进行测试,该API返回结果,并且工作正常。

但是使用下面的代码片段(axios),它将react应用程序的两个域和api Url连接到请求。

代码语言:javascript
代码运行次数:0
运行
复制
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时,它就像一个魔咒。

先谢谢你...

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 16:59:10

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

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

然后我使用它,如下所示:

代码语言:javascript
代码运行次数:0
运行
复制
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');
}

而且它工作得很完美。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53812984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档