首页 > 解决方案 > 如何解决:net::ERR_CONNECTION_REFUSED 将数据获取到 React 时?

问题描述

我正在尝试使用 axios 让这个 API 调用工作:

const getData = () => {
    Axios.get("http://localhost:3000/security?select=symbol,company",
    {headers: {Authorization: 'Bearer 73Ntx3b6SwNXC7ANV3tw4wFfDdKntB26',
                "Access-Control-Allow-Origin": "*",
                mode: "cors",               
    }}
    ).then((response) => {
        console.log(response)
    })
}

我的本地 API 服务器已启动并正在运行,我可以使用curlJSON 数据发出请求并查看。GET但是,当我在我的 React 应用程序中实现请求时,这些调用不起作用。

我有点想知道为什么会出现这些错误:

Failed to load resource: net::ERR_CONNECTION_REFUSED
createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)
createError @ createError.js:16
handleError @ xhr.js:84

有些东西阻止了 API 显示数据,我认为它是 React。在我的堆栈中,这种与localhost:3000API 的连接只在上面的代码中使用过一次,它只是检索唯一的数据......

关于如何解决的任何想法?

编辑:我添加了一张图片以显示端口已启动并且我的 API 已启动 在此处输入图像描述

编辑编辑:所以我在生产中测试了我的 API,看看它是否是一个后端问题,我可以从一个真实的网址实时访问我的 API。那里没有问题。我想我把我的后端修改得更接近于让 API 请求与 React 一起工作,因为现在我得到的是一个401 unauthorized Request而不是我之前的错误。

这是我的 api url 的 nginx 后端的配置文件:

    location /data/ {
      default_type  application/json;
      proxy_hide_header Content-Location;
      add_header Content-Location  /data/$upstream_http_content_location;
      add_header Access-Control-Allow-Origin *;
      proxy_set_header  Connection "";
      proxy_http_version 1.1;
      proxy_pass http://localhost:3000/;
        }
}

我还为上面的 REACT 获取请求添加了新代码。

标签: javascriptreactjsnginxaxiospostgrest

解决方案


尝试设置 Axios baseURL: 'http://localhost:3000' 并添加选项mode: "cors"


推荐阅读