【问题标题】:origin 'http://localhost:4200' has been blocked by CORS policy in Angular7Angular7 中的 CORS 策略已阻止源“http://localhost:4200”
【发布时间】:2019-10-13 04:07:05
【问题描述】:

我想在我的 Angular 项目中使用 http://5.160.2.148:8091/api/trainTicketing/city/findAll 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.

在浏览器和邮递员中输入网址时正常工作。

为什么?

【问题讨论】:

  • 这听起来可能很奇怪,但我不必在服务器端进行任何更改。 angular ui 项目有两个分支,一个正在处理另一个它不是。我还没有找到确凿的答案。

标签: angular


【解决方案1】:

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

解决方案 2 - 使用 Angular 代理 see here

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

解决方案 3 - 如果您的后端接受来自 *.mydomain.com 等通配符域的请求,然后您可以编辑您的 hosts 文件并在其中添加 127.0.0.1 local.mydomain.com,然后改为在浏览器中的localhost:4200 输入local.mydomain.com:4200

注意:它通过邮递员工作的原因是邮递员不会在您的浏览器发送预检请求时发送。

【讨论】:

    【解决方案2】:

    对于 .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(); 
    
          ...
    
         }
    

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

    【讨论】:

    • 这对我有用。我改变了订单,它奏效了。谢谢!
    【解决方案3】:

    如果你使用spring boot,你应该在@CrossOrigin注解中添加源链接

    @CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/yourPath")
    

    您可以在https://spring.io/guides/gs/rest-service-cors/找到详细说明

    【讨论】:

    • 问题与javascript有关,不认为spring boot解决方案适用
    • @CamiloCasadiego 它适用于我正在寻找的东西 :) 谢谢!
    【解决方案4】:

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

    'Access-Control-Allow-Origin', '*'
    'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'
    

    如果您可以访问服务器,则可以添加它们,这将解决您的问题

    您可以尝试在 url 前面连接这个:

    https://cors-anywhere.herokuapp.com/
    

    【讨论】:

      【解决方案5】:

      按照这些步骤进行

      1. 添加 cors 依赖项。在项目目录中的 cli 中键入以下内容

      npm install --save cors

      1. 在项目中包含模块

      var cors = require('cors');

      1. 终于把它当做中间件了。

      app.use(cors());

      【讨论】:

      • 这个解决方案是 Angular 的吗?还是 node.js 服务器?
      • 解决方案在node.js服务器中
      【解决方案6】:

      你们都擅长 Angular 方面,即使邮递员没有提出 cors 政策问题。 此类问题主要在后端解决。

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

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

      如果使用 spring boot 进行全局配置,请配置以下两个类:

      `

      @EnableWebSecurity
      @AllArgsConstructor
      
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      @Override
          public void configure(HttpSecurity httpSecurity) throws Exception{
              httpSecurity.csrf().disable()
              .authorizeRequests()
              .antMatchers("/api1/**").permitAll()
              .antMatchers("/api2/**").permitAll()
              .antMatchers("/api3/**").permitAll()
              
      }
      `
      
      @Configuration
      @EnableWebMvc
      public class WebConfig implements WebMvcConfigurer {
      
          @Override
          public void addCorsMappings(CorsRegistry corsRegistry) {
              corsRegistry.addMapping("/**")
                      .allowedOrigins("http://localhost:4200")
                      .allowedMethods("*")
                      .maxAge(3600L)
                      .allowedHeaders("*")
                      .exposedHeaders("Authorization")
                      .allowCredentials(true);
          }
      

      【讨论】:

      • 同意@shyam。这是要解决的后端(其余 API 服务器)问题,而不是 Angular 前端。我遇到了同样的问题,修复后端配置是正确的方法。
      【解决方案7】:

      对于开发期间的临时测试,我们可以通过像这样打开禁用网络安全的 chrome 来禁用它。

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

      输入这个命令:

      chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

      将打开一个新的浏览器窗口,并禁用网络安全。仅用于测试您的应用。

      【讨论】:

        【解决方案8】:

        WebAPI 中的 Startup.cs。

        app.UseCors(options => options.AllowAnyOrigin());  
        

        在 ConfigureServices 方法中:

        services.AddCors(c =>  
        {  
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
        });
        

        在控制器中:

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

        【讨论】:

          【解决方案9】:

          如果您的项目是 .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();
                  });
          
                 
              }
          }
          

          【讨论】:

          • 使用 .netcore 3.1 和 angular 12 为我工作
          【解决方案10】:

          nodejs 使用下面的代码

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

          【讨论】:

            【解决方案11】:

            1: 创建一个 WebMvcConfig 类并按照 WebMvcConfiguration 所示对其进行扩展,并覆盖 addCorsMappings 方法。

            2: 最重要的是不要忘记将其设为 @Configuration 注释,因为它应该与 Main Spring 类一起加载以允许跨域。

              @Configuration
                public class WebMvcCofig implements WebMvcConfigurer{
                    @Override
                    public void addCorsMappings(CorsRegistry registry) {
                        registry.addMapping("/*")
                                .allowedOrigins("*")
                                .allowedMethods("*")
                                .allowedHeaders("*")
                                .allowCredentials(true);
                    }
                }
            

            【讨论】:

              【解决方案12】:

              在我使用 Angular 和 Spring Boot 的情况下,我在 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>
              

              【讨论】:

                【解决方案13】:

                创建一个类并在spring boot应用中添加如下配置。

                    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);
                        }
                    }
                

                【讨论】:

                  【解决方案14】:

                  我尝试了上面给出的所有解决方案,并在使用 nodejs 后端时工作,但不幸的是,在使用 python 时它工作正常,所以我最终安装了一个插件Allow CORS,至少这个插件有帮助

                  【讨论】:

                    【解决方案15】:

                    如果您使用 spring-boot 进行服务器端编码,请添加 servlet 过滤器 并添加您的 spring-boot 应用程序的以下代码。它应该工作。添加"Access-Control-Allow-Headers", "*" 是强制性的。不需要创建 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);
                        }
                    }
                    

                    【讨论】:

                      【解决方案16】:

                      我尝试在快速服务器上的 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
                      })
                      

                      【讨论】:

                        【解决方案17】:

                        如果你使用 Spring boot 2,你可以在控制器类中添加 CrossOrigin 注解

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

                        它对我有用!

                        【讨论】:

                          【解决方案18】:

                          在 Spring Boot 中处理 COR 问题的方法有很多,最简单的方法就是将 @CrossOrigin 注解放在 Controller 的顶部,可能在您的 ..resource java 文件中。试试

                          @CrossOrigin(origins= {"*"}, maxAge = 4800, allowCredentials = "false" @RestController

                          有关更多信息,请阅读 spring boot CORs 文档。谢谢。

                          【讨论】:

                            【解决方案19】:

                            如果您将 Angular 与 Dotnet Core 一起使用:

                            关于 Startup.cs 类

                            在方法 ConfigureServices 添加:

                            services.AddCors();
                            

                            关于方法配置添加

                            app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200"));
                            

                            【讨论】:

                              【解决方案20】:

                              就我而言,我看到了错误:

                              Access to XMLHttpRequest at 'localhost:5000/graphql' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, chrome-untrusted, https.
                              

                              确保在您的网址中包含协议(http 或 https)。

                              const uri = 'http://localhost:5000/graphql'; // 
                              

                              【讨论】:

                                【解决方案21】:
                                • 如果您使用的是 Spring Boot 应用程序,则只需添加 @CrossOrigin 在您的控制器中并导入语句导入 org.springframework.web.bind.annotation.CrossOrigin;那套和 再次运行应用程序

                                【讨论】:

                                  【解决方案22】:

                                  如果你使用 node 作为后端,你可以使用它。只需在 Node.js 的 server.js“API”端添加这些行,在此之前确保安装“cors”

                                  const express = require('express');
                                  const app = express();
                                  app.use(express.json());
                                  var cors = require('cors');
                                  app.use(cors());
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    Java CROS 策略中的普通 REST API

                                    @GET
                                    @Path("getsample")
                                    @Produces(MediaType.APPLICATION_JSON)
                                    public Response getOptions() {
                                           Map<String,String> map=new HashMap<String,String>();
                                           // map.put("response",res); 
                                            map.put("name","Ajay");
                                             map.put("id","20");
                                             map.put("clg", "SLICA");
                                         
                                      return Response.ok()
                                        .header("Access-Control-Allow-Origin", "*")
                                        .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
                                        .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
                                        .entity(map)    
                                        .build();
                                      
                                    }
                                    

                                    【讨论】:

                                      猜你喜欢
                                      • 2019-12-29
                                      • 2020-07-09
                                      • 2020-01-26
                                      • 2019-10-31
                                      • 2021-01-20
                                      • 1970-01-01
                                      • 2019-11-17
                                      • 2020-10-12
                                      • 2019-11-16
                                      相关资源
                                      最近更新 更多