【发布时间】:2020-12-23 16:04:06
【问题描述】:
大家好,我在从 iOS 和 Android 模拟器调用我的 .net-core 服务器的 api 时遇到问题,而从浏览器中它可以工作。 在我的后端启用了 CORS:
public void ConfigureServices(IServiceCollection services){
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
if (env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseEndpoints(endpoints =>{
endpoints.MapControllers();
});
}
axios GET 服务:
export function axiosGet():Promise<any>{
const url = "https://localhost:5004/api/Aliments/";
return axios.get(url)
.then(response => {
return response.data;
})
.catch(error => {
console.log(error);
});
};
在您看来,为什么当我从 IOS/Android 模拟器调用 API 时会返回此错误?
Error: Network Error
at createError (createError.js:16)
at EventTarget.handleError (xhr.js:84)
at EventTarget.dispatchEvent (event-target-shim.js:818)
at EventTarget.setReadyState (XMLHttpRequest.js:600)
at EventTarget.__didCompleteResponse (XMLHttpRequest.js:395)
at XMLHttpRequest.js:508
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:416)
at MessageQueue.js:109
at MessageQueue.__guard (MessageQueue.js:364)
编辑 1 我尝试更改 192.168.1.104 中的主机 ip(是托管我的服务器的局域网 ip)
这是我的launchSettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:59803",
"sslPort": 44303
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "MyApp",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MyApp": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "MyApp",
"applicationUrl": "https://192.168.1.104:5004;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
【问题讨论】:
-
你的模拟器连接到互联网了吗?
-
模拟器以局域网模式连接,因为我使用的是expo。
标签: android ios react-native .net-core axios