在ASP .NET Core 2.1 Web Api中启用CORS

编程入门 行业动态 更新时间:2024-10-24 14:16:33
本文介绍了在ASP .NET Core 2.1 Web Api中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在ASP.NET Core 2.1 Web API和React中编写应用程序.我的服务器位于localhost:5000上,我的客户端位于localhost:3000上.我想用axios发送发帖请求,但是在浏览器控制台中我看到错误:

I'm writting application in ASP .NET Core 2.1 Web API and React. I have my server on localhost:5000 and my client on localhost:3000. I wanted to send post request with axios but in browser console i see error:

OPTIONS 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,但它似乎不起作用.我添加:

In my Web API I try to add CORS but it doesn't seems to work. I add:

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: 'localhost:5000/api/auth/login', data: { userName: this.state.controls.login.value, password: this.state.controls.password.value } });

请求后的服务器控制台:

Server console after request:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 OPTIONS 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 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.

当我使用邮递员时,一切都很好.我从服务器收到带令牌的json.

When I use Postman everything is fine. I receive json with token from server.

推荐答案

好,我解决了我的问题.我只是不知道我应该删除"app.UseHttpsRedirection();".

Ok, I resolve my problem. I just didn't know that I should remove "app.UseHttpsRedirection();".

更多推荐

在ASP .NET Core 2.1 Web Api中启用CORS

本文发布于:2023-11-10 09:34:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   NET   ASP   CORS   Api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!