简体   繁体   English

ReactJS/ASP.Net Core 2.1 版本 CORS 错误

[英]ReactJS/ASP.Net Core 2.1 Version CORS Error

When I do axios post by React JS, I get the following CORS error to ASP.Net Core side.当我通过 React JS 发布 axios 时,我在 ASP.Net Core 端收到以下 CORS 错误。

Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.无法加载资源:Access-Control-Allow-Origin 不允许来源 http://localhost:3000。 https://localhost:5001/api/vendorregistration https://localhost:5001/api/vendorregistration

I installed the following as my Nuget Packages and did not apply any other form below but it didn't work.我安装了以下作为我的 Nuget 包,并没有应用下面的任何其他形式,但它没有用。

  • Microsoft.AspNet.Cors. Microsoft.AspNet.Cors。 5.2.7 Version 5.2.7 版本
  • Microsoft.AspNetCore.Cors 2.1.1 Version Microsoft.AspNetCore.Cors 2.1.1版本

How to enable Cors for every type of request in asp.net core 3.1 如何为asp.net core 3.1中的每种类型的请求启用Cors

Startup.cs启动.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
        {
            builder.AllowAnyHeader()
                   .AllowAnyMethod()
                   .AllowAnyOrigin();
               //    .AllowCredentials();
        }));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseHttpsRedirection();

        app.UseCors("ReactPolicy");
        app.UseMvc();

    }
}

VendorRegistrationController.cs VendorRegistrationController.cs

namespace Bait.Controllers
{

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]

ReactJS Side RegistrationForm.tsx ReactJS Side RegistrationForm.tsx

 const handleFormSubmit = async (values: any): Promise<any> => {
   const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values })
   console.log(response);
 };

Could you pls check my code snippet as it worked for me.您能否检查我的代码片段,因为它对我有用。 I copied your startup file so I just put the using packages here.我复制了你的启动文件,所以我只是把使用包放在这里。

My test controller:我的测试controller:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace WebAppMVCcore2.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("ReactPolicy")]
    public class HelloController : Controller
    {
    
        [HttpPost]
        public string Index()
        {
            return "hello";
        }
    }
}

And my startup file:我的启动文件:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebAppMVC_core2
{}

And my test react code:我的测试反应代码:

import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount(){
      const response = axios.post('https://localhost:44326/api/hello').then(res=>{
        console.log('res=>',res);            
      })
      console.log(response);
  }
  
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

在此处输入图像描述

you do not have to use in every actions in the controller. just put app.UseCors("ReactPolicy");您不必在 controller 中的每个操作中使用。只需将 app.UseCors("ReactPolicy"); line before app.UseStaticFiles(); line app.UseStaticFiles(); line app.UseStaticFiles(); line

app.UseCors("ReactPolicy");

Hope it'll work!希望它能奏效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM