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

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

问题描述

我正在将 http 请求从我的 Angular 客户端应用程序发送到 .NET Core Web API.尽管我启用了 CORS,但我收到了 CORS 错误.当我向 SearchController 发送 GET 请求时,该请求通过得很好,但是当我向 FormController 发送 POST 请求时,我收到了 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 请求

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天全站免登陆