代码之家  ›  专栏  ›  技术社区  ›  Willy

React AXIOS将窗口原点附加到提供的URL(JSON服务器)

  •  0
  • Willy  · 技术社区  · 6 年前

    我在将JSON服务器API与AXIOS集成时有一种奇怪的行为。

    我使用json服务器提供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

    请求URL: http://localhost:3000/http//localhost:4000/tasks

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

    知道为什么会这样吗?

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

    事先谢谢…

    1 回复  |  直到 6 年前
        1
  •  0
  •   Willy    6 年前

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

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

    而且效果很好。