SpringBoot : No 'Access-Control-Allow-Origin' Access-Control-Allow-Origin

Points To Remember

This error occurs when

  • your server does not allow cross domain headers
  • your application does not allow cross domain headers
  • custom headers provided by request is not accepted by the application

How to Solve : No 'Access-Control-Allow-Origin' Access-Control-Allow-Origin error

In order to allow cross domain ajax calls to your Server you need to allow the Cross Domian Headers in your application.

You can allow the cross domain requests from your application in Spring boot by adding a CORS Filter as shown below.

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");

Here you need to specify the

  • Headers your application accepts as a comma separated Header keys like "X-Custom-Header"
  • Max age for the requests
  • Methods that your application allows 
  • Origins that your application allows. In example above we have specified "*", it means it will allow requests from all origins. You can give comma separated values to allow, access from your domains only.
You can set CORS using spring boot default configurations, as shown below.
endpoints.cors.allow-credentials=# Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers=# Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins=# Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers=# Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.

You can use custom Filter to set CORS , Full example, how to use CorsFilter is shown below.

No comments :

Post a Comment