简体   繁体   English

反应:Axios 网络错误

[英]React: Axios Network Error

This is my first time using axios and I have encountered an error.这是我第一次使用axios,遇到了一个错误。

  axios.get(
    `http://someurl.com/page1?param1=1&param2=${param2_id}`
  )
  .then(function(response) {
    alert();
  })
  .catch(function(error) {
    console.log(error);
  });

With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.使用正确的 url 和参数,当我检查网络请求时,我确实从我的服务器得到了正确的答案,但是当我打开控制台时,我发现它没有调用回调,而是捕获了一个错误。

Error: Network Error Stack trace: createError@ http://localhost:3000/static/js/bundle.js:2188:15 handleError@ http://localhost:3000/static/js/bundle.js:1717:14错误:网络错误堆栈跟踪:createError@ http://localhost:3000/static/js/bundle.js:2188:15 handleError@ http://localhost:3000/static/js/bundle.js:1717:14

If Creating an API Using NodeJS如果使用 NodeJS 创建 API


Your Express app needs to use CORS (Cross-Origin Resource Sharing). 您的 Express 应用程序需要使用 CORS(跨源资源共享)。 Add the following to your server file: 将以下内容添加到您的服务器文件中:

 // This should already be declared in your API file var app = express(); // ADD THIS var cors = require('cors'); app.use(cors());

For fuller understanding of CORS, please read the Mozilla Documentation on CORS .为了更全面地了解 CORS,请阅读关于 CORSMozilla 文档

my problem was about the url I was requesting to.我的问题是关于我请求的网址。 I hadn't inserted http:// at the beginning of my url.我没有在 url 的开头插入http:// I mean I was requesting to a url like 92.920.920.920/api/Token instead of http://92.920.920.920/api/Token .我的意思是我请求一个像92.920.920.920/api/Token而不是http://92.920.920.920/api/Token的网址。 adding http:// solved my problem.添加http://解决了我的问题。

除了@jacobhobson 的回答之外,我还使用了一些参数来使其工作。

app.use(cors({origin: true, credentials: true}));

I was having same issue on production on digital ocean droplet.我在制作数字海洋液滴时遇到了同样的问题。 I was using axios in ReactJS to call Node.js API.我是用在ReactJS Axios公司拨打Node.js的API。

Although I included cors虽然我包括了 cors

const cors = require('cors');
app.use(cors());

But I still had to add但我还是要补充

res.header( "Access-Control-Allow-Origin" );

before calling out my controller.在调用我的控制器之前。 And it worked for me.它对我有用。 There I realized that cors is not working properly.在那里我意识到 cors 无法正常工作。 So I uninstalled and installed them again and It Works!所以我卸载并再次安装它们,它有效!

Complete code is here.完整代码在这里。

So either you use所以无论你使用

 app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "x-access-token, Origin, X-Requested-With, Content-Type, Accept");
  next();
});

or use或使用

app.use(cors());

It's the same.这是一样的。

确保cors({ origin : [ "http://localhost:3001"]}).env文件中的端口号相同。

It happens when you work on localhost and forgot to add http://当您在本地主机上工作而忘记添加http://时会发生这种情况

Wrong Usage错误使用

  const headers = {
    "Content-Type": "application/json",
    Authorization: apiKey,
  };
  const url = "localhost:5000/api/expenses/get-expenses";

  axios.get(url, { headers });

  // NETWORK ERROR

The correct one is正确的是

  const headers = {
    "Content-Type": "application/json",
    Authorization: apiKey,
  };
  const url = "http://localhost:5000/api/expenses/get-expenses";

  axios.get(url, { headers });

  // WORKS FINE IF YOU HANDLED CORS CORRECTLY IN THE SERVER SIDE

I received a network error with axios 0.27.2 when I was trying to upload an image to our server.当我尝试将图像上传到我们的服务器时,我收到了 axios 0.27.2 的网络错误。 After I set headers like below no error is received.在我设置如下标题后,没有收到错误。

headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"}

and you need to check with your api request's body type in your collection like if it's form-data or x-wwww-form-urlencoded or ..etc.并且您需要检查您的集合中的 api 请求的主体类型,例如它是 form-data 还是 x-wwww-form-urlencoded 或 ..etc。

In my case it happened when my internet connection was unstable.就我而言,它发生在我的互联网连接不稳定时。 Make sure your internet connection is stable.确保您的互联网连接稳定。

就我而言,我使用了“ https ”而不是“ http ”,也请检查一下。

In my case I had set all the needed configs mentioned above in NodeJs but I still got the error.就我而言,我已经在 NodeJs 中设置了上面提到的所有需要​​的配置,但我仍然遇到错误。 I was using port 6000 in NodeJs and then I changed it to port 5000 and the problem was solved.我在 NodeJs 中使用了6000端口,然后将其更改为5000端口,问题解决了。
So just change the port if you have done all the alternatives.因此,如果您已完成所有替代方案,只需更改端口即可。

This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources.之所以会发生这种情况,是因为 restrict-origin-when-cross-origin 策略。浏览器发送一个飞行前请求以了解 API 服务器想要共享资源的对象。 So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.因此,您必须在 API 服务器中设置来源并发送一些状态。之后浏览器允许将请求发送到 API 服务器。

Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.这是代码。我在 localhost:8000 上运行前端,而 api 服务器在端口 6000 上运行。

const cors = require("cors");

app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));

app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));

I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource.我已将 origin 设置为我的前端 url,如果您将其设置为 true ,那么它将仅允许端口 8000 访问 rosource,并且运行在端口 8000 上的前端无法访问此资源。 Use this middleware before route in api server.在 api 服务器中路由之前使用此中间件。

就我而言,当我通过 cors origin:http://localhost:3000 时,我在 localhost:3001 上运行应用程序

检查您的服务器是否正在运行并且您的 API 是否已连接到数据库。

"

I have resolved my issue by adding this header.我通过添加此标头解决了我的问题。

var data = new FormData();
              data.append('request', 'CompaniesData');
           var config = {
                 method: 'post',
                 url: baseUrl, headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"},
                    data : data
                  };
            
                 axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });

i'm using axios in react-native as android and .net as backend, i have same issue but i can't solve the problem.我在 react-native 中使用 axios 作为 android 和 .net 作为后端,我有同样的问题,但我无法解决问题。 I think it is security problem when i type the url in chrome it warns me about that in emulator.我认为这是安全问题,当我在 chrome 中键入 url 时,它会在模拟器中警告我。

axios("http://10.0.2.2:5001/api/Users/getall")
  .then((result) => setUsers(result.data.data))
  .then((json) => {
    return json.data;
  })
  .catch((error) => {
    console.error(error);
  })
  .then((response) => response.parse());

In my case, I'm using Hapi.js as the backend, so all I had to do is set the cors value to true as in the code below;就我而言,我使用 Hapi.js 作为后端,所以我所要做的就是将 cors 值设置为 true,如下面的代码所示;

const server = Hapi.server({
       port: 4000,
       host: 'localhost',
       state: {
           strictHeader: false
       },
       routes: {
           cors: true
       }
});

Spent around 2 hours checking each routes and configs.花了大约 2 个小时检查每条路线和配置。 Finally found my mistake, I used URL="https://localhost:3000" instead of URL="http://localhost:3000"终于发现我的错误了,我用的是URL="https://localhost:3000"而不是URL="http://localhost:3000"

For Expo React Native, I had to change the baseURL to: http://10.0.2.2:[PORT] instead of localhost or http://127.0.0.1:[PORT]对于 Expo React Native,我必须将 baseURL 更改为:http://10.0.2.2:[PORT http://10.0.2.2:[PORT]而不是 localhost 或http://127.0.0.1:[PORT]

This is probably due to the emulator routing traffic through this address.这可能是由于模拟器通过此地址路由流量。

  1. change the port number of your node server.更改节点服务器的port号。 It took more than 3 hours to solve this error.解决这个错误花了3个多小时。 Solution ended with changing port numer which was initially set to 6000, later set to 3001. Then it worked.解决方案以更改端口号结束,该端口号最初设置为 6000,后来设置为 3001。然后它起作用了。 My server localhost base url was:我的服务器本地主机基础 url 是:

    "http://localhost:6000/data"

    I changed port number in app.listen() on server and from frontend I call that GET route in async function as await axios.get('http://localhost:3001/data') .我在服务器上更改了app.listen()中的端口号,从前端我将async function 中的GET路由称为await axios.get('http://localhost:3001/data') It is working fine now.现在工作正常。

  2. If you face the address issue: address already in use:::#port如果您遇到地址问题: address already in use:::#port

    Then on command prompt: killall -9 node然后在命令提示符下: killall -9 node

I just want to let you know that after searching for a solution for two days, I was able to solve my error.我只是想让你知道,在搜索了两天的解决方案之后,我能够解决我的错误。 Since the proxy was the source of the issue, I must configure a proxy in the package.json file, and I have to follow these instructions in the function that uses Axios:由于代理是问题的根源,我必须在 package.json 文件中配置代理,并且必须在使用 Axios 的函数中遵循以下说明:

try { await axios.post("user/login", formData).then((res) => { console.log(res.data); }); } catch (error) { console.log(error.response.data.message); }

and in package.json file need to add a proxy:并在 package.json 文件中需要添加一个代理:

"proxy": "http://localhost:6000",

for better understand check this documentation: enter link description here为了更好地理解,请查看此文档:在此处输入链接描述

for Node or (MERN) Application对于节点或(MERN)应用程序

Install cors with (npm i cors) and in your index.js or start file add使用 (npm i cors) 安装 cors 并在您的 index.js 或开始文件中添加

const express = require('express')
const app = express()
const cors= require('cors')
app.use(cors())

I hope your problem is solved我希望你的问题得到解决

检查是否安装了广告拦截器

When using Api使用 Api 时


Make sure that your url its whith确保你的网址是

  • https https

  • Not just http不仅仅是http

In my case, I didn't start the backend server.就我而言,我没有启动后端服务器。 Make sure your backend server is running.确保您的后端服务器正在运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM