【发布时间】:2021-03-16 13:22:41
【问题描述】:
我正在尝试在 .net core API (VS2019 .net core 2.2) 上测试一些性能问题
我可以使用 swagger 在本地机器上运行 API。
使用我在本地运行的 axios 调用从 ReactJS Web 应用程序调用 API。调用位于 Azure 服务器(dev、test、prod)上的 API 成功。
当我从 Web 应用程序调用本地 API 时,API 接收请求并返回响应,但在 Web 应用程序中没有收到响应。我收到此错误
错误:网络错误 在 createError (http://localhost:3000/static/js/0.chunk.js:149705:15) 在 XMLHttpRequest.handleError (http://localhost:3000/static/js/0.chunk.js:149256:14) {config: {…}, 请求:XMLHttpRequest,响应:未定义,堆栈:'错误:网络 错误 在 createError (http...ocalhost:3000/static/js/0.chunk.js:149256:14)',消息: “网络错误”}
我在类似的帖子中看到这可能是 CORS 问题。 API 将 CORS 设置为
app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
是否有人知道我可以尝试确定为什么我无法将 Web 应用程序连接到本地 api?
提前致谢 汉克
【问题讨论】:
-
指定
AllowAnyOrigin和AllowCredentials是不安全的配置,可能导致跨站点请求伪造。当应用配置了这两种方法时,CORS 服务返回无效的 CORS 响应。您可以将AllowAnyOrigin更改为WithOrigins("Specify the send request origin")。或者您可以将AllowAnyOrigin更改为.SetIsOriginAllowed(_ => true)。 -
@Rena,谢谢。这解决了 .net core 3.1 API 的类似问题,但 2.2 API 仍然无法正常工作 - 我将 use cors 行更改为 app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().WithOrigins( "localhost:3000").AllowCredentials());
-
嗨@Hank,嗯,我在评论中为您提供了两个解决方案,您的意思是第二个解决方案不适用于asp.net core 2.2,只有第一个有效?如果回答有帮助你,你能接受我下面的回答吗?参考:How to accept as answer。谢谢。
-
嗨@Rena,这两种解决方案都适用于 .net core 3.1 应用程序。通过启用 ssl 并将 Web 应用程序指向 https 地址,我让他们为 2.2 应用程序工作。再次感谢您的帮助。
标签: asp.net-core axios localhost