CORS: react + Spring = only OPTIONS is being sent

990 views java

CORS: react + Spring = only OPTIONS is being sent

Spring web config

   public void addCorsMappings(CorsRegistry registry) {
            .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS");

Tried CorsFilter

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

But for post

fetch('https://x/catalogs', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Origin': 'y',
      'Access-Control-Request-Method': 'POST'
  .then(function(response) {
      categories: response.json()
  .catch(error => {
    console.log("ERROR: ", error);

it sends only Options request.

Why? How fix this?

answered question

1 Answer


In your CorsFilter code, change this line:

response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

…to this:

response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with");

You need that because your fetch call is adding a Content-Type request header. In that case, the browser does a CORS preflight OPTIONS request (before sending the POST from your own code). And in order for the browser to decide that preflight has succeeded, the browser needs to see a response from the server with an Access-Control-Allow-Headers response header that has Content-Type in its value.

Also, from the fetch call in your JavaScript, remove these lines:

  'Origin': 'y',
  'Access-Control-Request-Method': 'POST'

That’s because, browsers don’t let you set the Origin or Access-Control-Request-Method headers — instead those both are headers added by the browser itself.

posted this

Have an answer?


Please login first before posting an answer.