跨源请求在HTTP POST请求上被阻止 [英] Cross Origin Request Blocked on HTTP POST request

查看:345
本文介绍了跨源请求在HTTP POST请求上被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的角度客户端应用程序向.NET Core Web API发送http请求。我启用了CORS,但出现CORS错误。当我将GET请求发送到SearchController时,一切正常,但是当我将POST请求发送到FormController时,出现了CORS错误。

I'm sending http requests from my angular client app to .NET core web API. I'm getting a CORS error although I enabled CORS. When I send a GET request to my SearchController that goes through just fine, but when I send a POST request to my FormController I get the CORS error.

在chrome中运行它,结果相同。

I've tried running it in chrome, same result.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }


            app.UseCors(builder =>
                builder.AllowAnyOrigin()
                );

            app.UseHttpsRedirection();
            app.UseMvc();
 }

如您所见,我已将其配置为允许任何来源

As you can see I have it configured to allow any origin

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token',

    })
};



@Injectable()

export class SendFormService
{
    submitUrl : string = "https://localhost:5001/api/submitForm";

    constructor(private http : HttpClient){ }

    public SendFormData(formData : RoadmapForm) : Observable<RoadmapForm>
    {
        //remember to error handle
        return this.http.post<RoadmapForm>(this.submitUrl, formData, httpOptions);

    }
}

POST请求无效/ p>

The POST request that's not working

    public class Form
    {
        string title;
        string summary;
        string body;
        string[] tags;

    }

    [Route("api/submitForm")]
    [ApiController]

    public class FormController : ControllerBase
    {
        [HttpPost]
        public void Post([FromBody] Form formData)
        {
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine(formData);
        }
    }

FormController类

The FormController class

就像我之前说的,它适用于对SearchController的GET请求。但是由于某种原因,我在向FormController发送POST请求时收到了CORS错误。

Like I said earlier it works for GET requests to my SearchController. But for some reason I get the CORS error on the POST request to my FormController.

推荐答案

启用CORS

public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
      services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
    );

    app.UseMvc();
}

这篇关于跨源请求在HTTP POST请求上被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆