原产地';http://localhost:4200' 已被Angular7的CORS政策阻止

原产地';http://localhost:4200' 已被Angular7的CORS政策阻止,angular,Angular,我想在我的angular项目中使用rest来获取城市。 我在项目中使用了angular的7.2.15版。 使用httpClient获取此url时抛出以下错误: Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to pr

我想在我的angular项目中使用rest来获取城市。
我在项目中使用了angular的7.2.15版。
使用httpClient获取此url时抛出以下错误:

 Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在浏览器和邮递员中输入url时工作正常。


为什么?

解决方案1-您需要更改后端以接受传入的请求

解决方案2-使用角度代理

请注意,这仅适用于
ng serve
,您不能在
ng build


注意:它通过postman工作的原因是,当浏览器发送飞行前请求时,postman不发送飞行前请求。

解决方案需要将这些头添加到服务器响应中

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'
如果您有权访问服务器,您可以添加它们,这将解决您的问题

您可以尝试在url前面包含以下内容:

https://cors-anywhere.herokuapp.com/
遵循以下步骤

  • 添加cors依赖项。在项目目录中的cli中键入以下命令
  • npm安装--保存cors

  • 将模块包含在项目中
  • var-cors=require('cors')

  • 最后,将其用作中间件
  • app.use(cors())


    如果使用spring boot,则应在@CrossOrigin注释中添加原点链接

    @CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/yourPath")
    
    您可以在WebAPI中的Startup.cs中找到详细说明

    app.UseCors(options => options.AllowAnyOrigin());  
    
    在ConfigureServices方法中:

    services.AddCors(c =>  
    {  
        c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
    });
    
    在控制器中:

    [HttpGet]  
         [Route("GetAllAuthor")]  
         [EnableCors("AllowOrigin")] 
    

    你们都擅长角边,即使邮递员不提出cors政策问题。 在主要情况下,这类问题在后端解决

    如果您使用的是SpringBoot,则可以通过将此注释放置在控制器类或任何特定方法中来避免此问题

    @CrossOrigin(origins = "http://localhost:4200")
    
    如果使用spring boot进行全局配置,请配置以下两个类:

    `

    1: 创建一个类WebMvcConfig,并按照WebMvcConfiguration和overrideaddCorsMappings方法所示对其进行扩展

    2: 最重要的是,不要忘记对其进行@Configuration注释,因为它应该加载主Spring类,以允许交叉原点

      @Configuration
        public class WebMvcCofig implements WebMvcConfigurer{
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*")
                        .allowedOrigins("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        }
    
    对于.NET CORE 3.1 在添加cors中间件之前,我使用了https重定向,并且能够通过更改它们的顺序来解决问题

    我的意思是:

    更改此选项:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
          ...
            
            app.UseHttpsRedirection();  
    
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
    
          ...
    
         }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
          ...
            
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
    
            app.UseHttpsRedirection(); 
    
          ...
    
         }
    
    对此:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
          ...
            
            app.UseHttpsRedirection();  
    
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
    
          ...
    
         }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
    
          ...
            
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
    
            app.UseHttpsRedirection(); 
    
          ...
    
         }
    

    顺便说一句,在生产阶段允许来自任何来源和方法的请求可能不是一个好主意,您应该在生产阶段编写自己的cors策略。

    如果您的项目是.net Core 3.1 API项目

    将.net核心项目中的Startup.cs更新为:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://localhost:53135",
                                        "http://localhost:4200"
                                        )
                                        .AllowAnyHeader()
                                        .AllowAnyMethod();
                });
            });
            services.AddDbContext<CIVDataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("CIVDatabaseConnection")));
            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.UseCors(MyAllowSpecificOrigins);
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
    
           
        }
    }
    
    公共类启动
    {
    公共启动(IConfiguration配置)
    {
    配置=配置;
    }
    公共IConfiguration配置{get;}
    只读字符串MyAllowSpecificCorigins=“\u MyAllowSpecificCorigins”;
    //此方法由运行时调用。请使用此方法将服务添加到容器中。
    public void配置服务(IServiceCollection服务)
    {
    services.AddCors(选项=>
    {
    options.AddPolicy(MyAllowSpecificCorigins,
    生成器=>
    {
    建筑商。来源(“http://localhost:53135",
    "http://localhost:4200"
    )
    .AllowAnyHeader()
    .AllowAnyMethod();
    });
    });
    services.AddDbContext(选项=>
    options.UseSqlServer(Configuration.GetConnectionString(“CIVDatabaseConnection”));
    services.AddControllers();
    }
    //此方法由运行时调用。请使用此方法配置HTTP请求管道。
    public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
    {
    if(env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    应用程序UseCors(MyAllowSpecificCorigins);
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(端点=>
    {
    endpoints.MapControllers();
    });
    }
    }
    
    如果您使用spring boot进行服务器端编码,请添加一个servlet过滤器,并添加spring boot应用程序的以下代码。它应该会起作用。必须添加
    “访问控制允许标头”、“*”
    。不需要创建proxy.conf.json

        @Component
    @Order(1)
    public class MyProjectFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res,
                FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Max-Age", "86400");
            chain.doFilter(req, res);
        }
    }
    

    对于开发过程中的临时测试,我们可以通过在禁用web安全性的情况下打开chrome来禁用它

    打开命令行终端并转到安装chrome的文件夹,即C:\ProgramFiles(x86)\Google\chrome\Application

    输入以下命令:

    chrome.exe--user data dir=“C:/chrome dev session”--禁用web安全性


    将打开一个新的浏览器窗口,其中禁用了web安全性。仅用于测试您的应用程序。

    在我的情况下,使用角形和弹簧启动我在SecurityConfig中解决了这个问题:

    http.csrf().disable().cors().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/register")
                .anonymous()
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    
    或将该行替换为:

    http.csrf().disable().cors().and()
    
    另一个测试选项是从pom.xml中删除依赖项,其他代码依赖于它。这就像从Spring关闭安全:

    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
         <version>2.3.3.RELEASE</version>
    </dependency>
    
    
    org.springframework.boot
    弹簧启动安全
    2.3.3.2发布
    
    对于
    nodejs
    使用以下代码

    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    

    我尝试在express服务器上的API上添加以下语句,它与Angular8一起工作

    app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET , PUT , POST , DELETE");
        res.header("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
        next(); // Important
    })
    

    如果使用SpringBoot2,则可以在控制器类中添加交叉原点注释

    @CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
    

    这对我有用

    创建一个类并在spring引导应用程序中添加以下配置

        package com.myapp.springboot.configs;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.web.servlet.config.annotation.CorsRegistry;
        import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
        
        @Configuration
        public class WebMvcConfiguration implements WebMvcConfigurer {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*").
                allowedOrigins("*").
                allowedMethods("*").
                allowedHeaders("*").
                allowCredentials(true);
            }
        }
    

    在spring boot中有很多方法可以处理CORs问题,最简单的方法就是将@CrossOrigin注释放在C语言的顶部
    app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200"));