【发布时间】:2019-01-24 18:31:28
【问题描述】:
我正在用 ASP .NET Core 2.1 Web API 和 React 编写应用程序。我的服务器在 localhost:5000 上,我的客户端在 localhost:3000 上。我想用 axios 发送 post 请求,但在浏览器控制台中我看到错误:
OPTIONS https://localhost:5001/api/auth/login 0 ()
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
在我的 Web API 中,我尝试添加 CORS,但它似乎不起作用。我补充:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
...
}
还有:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(options =>
options
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
...
app.UseMvc();
}
这是我的发帖请求:
const response = await axios({
method: 'post',
url: 'http://localhost:5000/api/auth/login',
data: {
userName: this.state.controls.login.value,
password: this.state.controls.password.value
}
});
请求后的服务器控制台:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 OPTIONS http://localhost:5000/api/auth/login
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 4.253ms 204
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 POST http://localhost:5000/api/auth/login application/json;charset=UTF-8 52
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 2.1805ms 307
info: Microsoft.AspNetCore.Server.Kestrel[32]
Connection id "0HLG4CH3JIV16", Request id "0HLG4CH3JIV16:00000002": the application completed without reading the entire request body.
当我使用 Postman 时,一切都很好。我从服务器收到带有令牌的 json。
【问题讨论】:
-
如果您在部署时不需要 COR,那么您可以仅为您的开发环境设置代理。你用什么作为你的开发网络服务器?
-
我使用 create-react-app 内置的开发服务器。如何设置代理?
-
好的,我在 package.json 中设置了代理,并将我在 axios 中的 url 更改为“/api/auth/login”,但在控制台中我仍然看到相同的内容。我不知道为什么它会将我重定向到 https 和端口 5001,即使我在代理中设置了 http 和端口 5000
-
即使我在 axios 配置中设置了代理,我仍然有同样的问题,没有任何改变
-
这可能会有所帮助。 github.com/facebook/create-react-app/issues/800。对不起,我没有太多反应。我已经让它以角度工作,但这是快递的不同包装。祝你好运