【问题标题】:react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource反应对 XMLHttpRequest 的访问已被 CORS 策略阻止 请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2020-06-24 14:51:08
【问题描述】:

我正在尝试从 api 访问数据,但出现此错误

从源“http://localhost:3000”访问“http://example.com/api/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许源” ' 请求的资源上存在标头。

这是我的代码

return axios.post('http://example.com/api/login', { username: username, password: password }).then(response => {
        console.log('response', response);

        if (response.status === 400 || response.status === 500)
            throw response.data;
        return response.data;
    }).catch(err => {
        console.log('err', err);

        throw err[1];
    });

使用 asp.net 构建的后端

谢谢

【问题讨论】:

    标签: asp.net reactjs api axios


    【解决方案1】:

    此问题与您的服务器有关。您的服务器不允许来自不同域的请求。在您的情况下,http://example.com/api/login 和 http://localhost:3000 位于不同的域中。您可以在您的 asp.net 代码中允许任何您想要的域。以下代码可能对您有用:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://example.com",
                                        "http://www.contoso.com");
                });
            });
    
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
    
            app.UseCors(MyAllowSpecificOrigins); 
    
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
    

    更多信息,您可以导航here

    【讨论】:

    【解决方案2】:

    经过几个小时的搜索,我找到了解决问题的这个 chrome 扩展 https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2021-12-27
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多