How to fix No ‘Access-Control-Allow-Origin’ header is present on requested resource?

Like the title says.

I am using Strapi v. 3.6.10.

Today I am getting the error that says: “Access to XMLHttpRequest at “server_url” from origin “frontend_url” has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

Until yesterday everything was working fine and here’s the middleware.js configuration up till yesterday:

module.exports = {
  settings: {
    parser: {
      textLimit: '10mb',
      formLimit: '10mb', // modify here limit of the form body
      jsonLimit: '10mb', // modify here limit of the JSON body
      formidable: {
        maxFileSize: 100 * 1024 * 1024, // multipart data, modify here limit of uploaded file size
      },
    },
  },
};

Today when it stopped working. I don’t know why, but then I made these changes to middleware.js but still it doesn’t work:

module.exports = {
  settings: {
    cors: {
      enabled: true,
      origin: ['*'],
      headers: [
        'Content-Type',
        'Authorization',
        'X-Frame-Options',
        'Origin',
        'Accept',
      ],
    },
    parser: {
      textLimit: '10mb',
      formLimit: '10mb', // modify here limit of the form body
      jsonLimit: '10mb', // modify here limit of the JSON body
      formidable: {
        maxFileSize: 100 * 1024 * 1024, // multipart data, modify here limit of uploaded file size
      },
    },
  },
};

None of the above configurations work. I have been trying to fix it for hours but no luck…

Your help would be greatly appreciated!

This error typically occurs in web development when making cross-origin requests. This error is related to the same-origin policy implemented by web browsers for security reasons. The same-origin policy restricts web pages from making requests to a different domain unless the server explicitly allows it by including the ‘Access-Control-Allow-Origin’ header in the response. To resolve this issue, the server hosting the requested resource needs to include the appropriate ‘Access-Control-Allow-Origin’ header, specifying the domain or origins allowed to access the resource. This can be done by configuring the server’s response headers or by using server-side middleware or frameworks that handle cross-origin requests.

JSON with Padding is just a way to circumvent same-origin policy, when CORS is not an option. This is risky and a bad practice. Avoid using this.

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

If you need to enable CORS on the server in case of localhost, you need to have the following on request header.

Access-Control-Allow-Origin: http://localhost:9999