反应:Axios 网络错误

React: Axios Network Error

我是第一次使用axios,遇到了一个错误。

  axios.get(
    `http://someurl.com/page1?param1=1&param2=${param2_id}`
  )
  .then(function(response) {
    alert();
  })
  .catch(function(error) {
    console.log(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

如果使用 NodeJS 创建 API


您的 Express 应用需要使用 CORS(跨源资源共享)。将以下内容添加到您的服务器文件中:

// This should already be declared in your API file
var app = express();

// ADD THIS
var cors = require('cors');
app.use(cors());

为了更全面地了解 CORS,请阅读 Mozilla Documentation on CORS

我的问题是关于 url 我请求的。我没有在 url 的开头插入 http://。我的意思是我请求 url,比如 92.920.920.920/api/Token 而不是 http://92.920.920.920/api/Token。添加 http:// 解决了我的问题。

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

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

我在数字海洋水滴的生产上遇到了同样的问题。我在 ReactJS 中使用 axios 来调用 Node.js API.

虽然我包含了 cors

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

但我还是要补充

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

在调用我的控制器之前。它对我有用。在那里我意识到 cors 无法正常工作。所以我卸载并重新安装它们并且它有效!

完整代码在这里。

所以要么你使用

 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();
});

或使用

app.use(cors());

都一样

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

当您在 localhost 上工作而忘记添加 http://

时会发生这种情况

错误用法

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

  axios.get(url, { headers });

  // NETWORK ERROR

正确的是

  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

就我而言,这是在我的互联网连接不稳定时发生的。请确保您的互联网连接稳定。

在我的例子中,我使用了“https”而不是“http”,也检查一下。

在我的例子中,我已经在 NodeJs 中设置了上面提到的所有需要​​的配置,但我仍然遇到错误。我在NodeJs中使用端口6000,然后将其更改为端口5000,问题就解决了。
因此,如果您已完成所有备选方案,只需更改端口即可。

发生这种情况是因为 restrict-origin-when-cross-origin policy.Browser 发送飞行前请求以了解 API 服务器想要共享资源的对象。 所以你必须在 API 服务器中设置 origin 并发送一些 status.After 浏览器允许将请求发送到 API 服务器。

这是 code.I am 运行 前端 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 }));

我已经将origin设置为我的前端url,如果你将它设置为true,那么它将只允许8000端口访问rosource,而前端运行在8000端口上无法访问此资源。在 api 服务器中的路由之前使用此中间件。

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

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

检查是否安装了AD拦截器

就我而言,我没有启动后端服务器。确保您的后端服务器是 运行.

当我尝试将图像上传到我们的服务器时,我收到了 axios 0.27.2 的网络错误。在我像下面这样设置 headers 之后,没有收到任何错误。

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

并且您需要检查 api 请求的 body 输入您的 collection 是否是 form-data 或 x-wwww-form-urlencoded 或..等等。

我已经通过添加 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);
    });

我在 react-native 中使用 axios 作为 android 和 .net 作为后端,我有同样的问题,但我无法解决问题。我认为这是安全问题,当我在 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());