reactjs CORS策略已阻止获取“提取”:React页面上不存在“访问控制允许来源”标题

8aqjt8rx  于 2022-12-26  发布在  React
关注(0)|答案(2)|浏览(124)

虽然我在.NET和Javascript方面很有经验,但我目前正在学习React,在获取REST API的过程中,我得到了这个错误。
CORS策略已阻止从源“http://localhost:3000”在“https://localhost:7142/api/Campaign”进行提取的访问:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以在禁用CORS的情况下提取资源。
这是我的Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace WebAPI
{
    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)
        {
            //Enable CORS
            services.AddCors(c => c.AddPolicy(name:"MyPolicy", options =>
            {
                options.WithOrigins("http://localhost:3000")
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            
            //JSON Serializer
            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
                = new DefaultContractResolver());

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            //Enable CORS
            app.UseCors("MyPolicy");

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                   Path.Combine(Directory.GetCurrentDirectory(), "Photos")),
                RequestPath = "/Photos"
            });
        }
    }
}

我相信这个问题必须处理CORS政策,但已经尝试了一切。有什么突出的人吗?
这是我的Campaign.js

import React,{Component} from 'react';
import { variables } from './Variables';

export class Campaign extends Component{
constructor(props){
    super(props);

    this.state={
        campaigns:[]
    }
}

refreshList(){ 
    debugger;
    //fetch(variables.API_URL+'Campaign')
    fetch('https://localhost:7142/api/Campaign')
    .then(response=>response.json())
    .then(data=>{
        this.setState({campaigns:data});
        console.log(data);
    });
}

componentDidMount(){
    this.refreshList();
}

    render(){
        const {
            campaigns
        }=this.state;

        return(
            <div>
                <table className='table table-striped'>
                    <thead>
                        <tr>
                            <th>
                                CampaignId
                            </th>
                            <th>
                                CampaignName
                            </th>
                            <th>
                                Options
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        {campaigns.map(camp=>
                            <tr key={camp.campaign_id}>
                                <td>{camp.campaign_id}</td>
                                <td>{camp.campaign_name}</td>
                                <td>
                                    <button type="button" className="btn btn-light mr-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
                                        <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
                                        <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
                                        </svg>
                                    </button>
                                    <button type="button" className="btn btn-light mr-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash-fill" viewBox="0 0 16 16">
                                        <path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/>
                                        </svg>
                                    </button>
                                </td>
                            </tr>
                            )}
                    </tbody>
                </table>
            </div>
        )
    }
}

export default Campaign;
aiqt4smr

aiqt4smr1#

希望我能帮助你..我也是新学习React和抓取。我遇到了这个问题,以及当我试图发送'POST'请求到一个真实的数据库在firebase。我已经修复了这个错误的方法是添加'folder-name.json'在我的网址我正在抓取的结尾。

async function addMovieHandler(movie) {
const response = await fetch('https://react-http-21af5-default-rtdb.firebaseio.com/movies.json' , {
  method: 'POST',
  body: JSON.stringify(movie),
  headers: {
    'Content-type' : 'application/json'
  }
})

const data = await response.json();
console.log(data);

}
如果这没有帮助,我读到你需要在你的后端服务器安装CORS来获取数据。你可能会在这个网站找到有用的信息[链接]:网站名称:http://www.stackhawk.com/blog/react-cors-guide-what-it-is-and-how-to-enable-it/#:~:文本= CORS%20错误。,在%20端口%203000上的客户端%20的React。

kknvjkwl

kknvjkwl2#

是的,这确实与CORS有关,跨源资源共享。因此,本质上,API从标识为localhost的服务器获取请求,这是另一个域,因此它是对象。
这是因为.net希望你作为一个开发者选择使用外部域数据,以被动地帮助你抵御DOS攻击。你要做的是告诉.net这个地方是可以的,或者选择允许所有地方,如果你是这样的人,所以在Startup.cs中配置API时

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
  //-- Obviously the kind citizen will be explicit about origins accepted, 
  // this is sort of a overruling in essence of the functionality, which 
  // is not necessarily ideal
  app.UseCors(
      x => x.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
  );
  if(YouFeel.LikeIt()){
     // alternative
     app.UseCors(
      x => x.WithOrigins(
              "http://www.yoursite.com",
              "http://localhost"       // this one should probably only run in develpment environment if you add
            ).AllowAnyMethod()
             .AllowAnyHeader()
      );
  }
}

相关问题