首页 > 解决方案 > 错误:React Native 出现网络错误,请求 .net core web api

问题描述

(AXIOS GET)

我要求.net core web api 2.1使用本机反应,但我在控制台上得到的错误如下:

注意: Cors 被授予权限.net core 2.1

代码:

return axios.get('http://127.0.0.1:50000/api/values', {
  credentials: 'include'
})
.then(
  (response) => {
    console.log(response);
  }
)
.catch(
  (error) => {
    console.log(error);
  }
);

错误:

Error: Network Error
    at createError (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\axios\lib\core\createError.js:16)
    at XMLHttpRequest.handleError (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\axios\lib\adapters\xhr.js:87)
    at XMLHttpRequest.dispatchEvent (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\event-target-shim\lib\event-target.js:172)
    at XMLHttpRequest.setReadyState (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:394)
    at D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190)
    at MessageQueue.__callFunction (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349)
    at D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106
    at MessageQueue.__guard (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297)

标签: reactjsreact-nativeasp.net-core-webapireact-web

解决方案


刚遇到同样的问题。

即使您没有收到CORS错误,您可能仍然缺少Access-Control-Allow-Origin仍然“错误”您的请求的标头。

您需要将 CORS 添加到您的 ASP.net 核心应用程序中。

services.AddCors(options =>
    options.AddPolicy("MyPolicy",
        builder => {
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        }
    )
);

接着

app.UseCors("MyPolicy");

app.UseMvc();

这很方便,并且允许向您的 API 发出任何ajax 请求,但它并不理想。

您可以允许您选择的 IP 和域。如何做到这一点阅读更多在 ASP.NET Core 中启用跨域请求 (CORS)


推荐阅读