origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Angular

Angular Problem Overview


I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.
I used version 7.2.15 of angular in my project.
when get this url with httpClient throw following error :

 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.

While at work correctly when enter url in browser and postman.

why ?

Angular Solutions


Solution 1 - Angular

Solution 1 - you need to change your backend to accept your incoming requests

Solution 2 - using Angular proxy see here

> Please note this is only for ng serve, you can't use proxy in ng build

Solution 3 - IF your backend accepts requests from a wildcard domanin like *.mydomain.com then you can edit your hosts file and add 127.0.0.1 local.mydomain.com in there, then in your browser instead of localhost:4200 enter local.mydomain.com:4200

Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.

Solution 2 - Angular

For .NET CORE 3.1

I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them

What i mean is:

change this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.

Solution 3 - Angular

if You use spring boot , you should add origin link in the @CrossOrigin annotation

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

You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/

Solution 4 - Angular

You are all good at Angular side even postman not raise the cors policy issue. This type of issue is solved at back-end side in major cases.

If you are using Spring boot the you can avoid this issue by placing this annotation at your controller class or at any particular method.

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

In case of global configuration with spring boot configure following two class:

`

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

Solution 5 - Angular

The solution needs to add these headers to the server response.

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

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

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

Solution 6 - Angular

Follow these steps

  1. Add cors dependency. type the following in cli inside your project directory

> npm install --save cors

  1. Include the module inside your project

> var cors = require('cors');

  1. Finally use it as a middleware.

> app.use(cors());

Solution 7 - Angular

Startup.cs in WebAPI.

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

In ConfigureServices method:

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

In Controller:

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

Solution 8 - Angular

For temporary testing during development we can disable it by opening chrome with disabled web security like this.

Open command line terminal and go to folder where chrome is installed i.e. C:\Program Files (x86)\Google\Chrome\Application

Enter this command:

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

A new browser window will open with disabled web security. Use it only for testing your app.

Solution 9 - Angular

If your project is .net Core 3.1 API project.

update your Startup.cs in your .net core project to:

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

       
    }
}

Solution 10 - Angular

For nodejs use the below code

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

Solution 11 - Angular

1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.

2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.

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

Solution 12 - Angular

In my case using Angular and Spring Boot I solved that issue in my SecurityConfig:

http.csrf().disable().cors().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/register")
            .anonymous()
            .anyRequest().authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

Or replace that line to:

http.csrf().disable().cors().and()

And other test option is to delete dependency from pom.xml and other code depend on it. It's like turn off security from Spring:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
     <version>2.3.3.RELEASE</version>
</dependency>

Solution 13 - Angular

Create a class and add the below configuration in the spring boot application.

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

Solution 14 - Angular

I tried all the solutions given above and worked while using nodejs backend but unfortunately while working with python it dint work, so I ended up installing a plugin Allow CORS, atleast this plugin helped

Solution 15 - Angular

If you are using spring-boot for server side coding then please add a servlet filter and add the following code of your spring-boot application. It should work. Adding "Access-Control-Allow-Headers", "*" is mandatory. Creation of proxy.conf.json is not needed.

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

Solution 16 - Angular

I Tried adding the below statement on my API on the express server and it worked with 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
})

Solution 17 - Angular

  • If you are using spring boot application then just add @CrossOrigin in your Controller and import the statement import org.springframework.web.bind.annotation.CrossOrigin; that set and run the application again

Solution 18 - Angular

If you use Spring boot 2 you can add CrossOrigin annotation in the controller class

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

it worked for me !

Solution 19 - Angular

There are so many ways to handle the issue of CORs in spring boot, the easiest way is to just put the @CrossOrigin annotation on top of the Controller may be in your ..resource java file. Try

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

for more info read spring boot CORs docs. Thank you.

Solution 20 - Angular

If you are using Angular with Dotnet Core:

On class Startup.cs

On method ConfigureServices add:

services.AddCors();

On method Configure add

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

Solution 21 - Angular

In my case I saw the error:

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.

Make sure to include a protocol (http or https) in your urls.

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

Solution 22 - Angular

If you using node as a backend you can use this. Just add these lines on the server.js "API" side in Node.js, before that make sure to install "cors"

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

Solution 23 - Angular

> Normal REST API IN JAVA CROS POLICY

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

Solution 24 - Angular

If by Any chance you are using fireBase as a dataBase you need to add ".json" to the end of the link, this solved the issue for me

cors error: https://uar-test-bd448-default-rtdb.firebaseio.com/rules

NO ERROR: https://uar-test-bd448-default-rtdb.firebaseio.com/rules.**json**

Solution 25 - Angular

if using Nodejs(Back-End) with application angular install the cors in NodeJs npm install --save cors

var cors = require('cors');

app.use(cors());

Solution 26 - Angular

Nestjs

app.enableCors({ origin: "*" });

Allows any origin. I recommend only allowing this in development mode.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionor123456View Question on Stackoverflow
Solution 1 - AngularRezaView Answer on Stackoverflow
Solution 2 - AngularokanView Answer on Stackoverflow
Solution 3 - AngularwhitefangView Answer on Stackoverflow
Solution 4 - Angularshyam viraniView Answer on Stackoverflow
Solution 5 - AngularOrestis ZekaiView Answer on Stackoverflow
Solution 6 - AngularAbdulhakim ZeinuView Answer on Stackoverflow
Solution 7 - AngularĐỗ Khắc ĐôngView Answer on Stackoverflow
Solution 8 - AngularMuzaffar MahmoodView Answer on Stackoverflow
Solution 9 - AngularMJ XView Answer on Stackoverflow
Solution 10 - AngularAneesh AhamedView Answer on Stackoverflow
Solution 11 - AngularA.K.J.94View Answer on Stackoverflow
Solution 12 - AngularmzhehaloView Answer on Stackoverflow
Solution 13 - AngularsubhashisView Answer on Stackoverflow
Solution 14 - AngularJohn WanjohiView Answer on Stackoverflow
Solution 15 - AngularAnupamView Answer on Stackoverflow
Solution 16 - AngularRishabhView Answer on Stackoverflow
Solution 17 - Angularpriya ghuleView Answer on Stackoverflow
Solution 18 - AngularAnis KCHAOUView Answer on Stackoverflow
Solution 19 - AngularJasperView Answer on Stackoverflow
Solution 20 - AngularConsuleView Answer on Stackoverflow
Solution 21 - AngularEnricoView Answer on Stackoverflow
Solution 22 - AngularShubham LoharView Answer on Stackoverflow
Solution 23 - AngularAJAY KACHHIYAPATELView Answer on Stackoverflow
Solution 24 - AngularBojidariView Answer on Stackoverflow
Solution 25 - AngularAirton DomicianoView Answer on Stackoverflow
Solution 26 - AngularRoyer AdamesView Answer on Stackoverflow