reactjs - 错误: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)
解决方案
刚遇到同样的问题。
即使您没有收到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)
推荐阅读
- kubernetes - Knative 大使 Ingress
- php - 在 Linux 上从 PHP 连接到 MS Access 数据库
- javascript - 有没有办法为Oracle中的文件定义一个新目录
- sql - 完全外连接在右侧没有获得 NULL 值,而它们确实存在于左侧
- node.js - 如何在 npm gulp maven deploy 插件中传递用户名和密码
- php - 试图在laravel中获取非对象的属性“状态”
- powershell - 格式化来自 docker 事件的 json 输出
- javascript - 如何仅禁用上个月的日期
- android - 如何解决重复的 gradle 依赖项(jsr305)?
- list - 如何检查1000s目录中的配对文件