10

I'm using strapi 4 as localhost and got a problem with cors settings when I add new assets via url

Image upload takes CORS error Access to XMLHttpRequest at 'https://www.countrysideveterinaryclinic.org/sites/default/files/interesting-cat-facts.jpg' from origin 'http://localhost:1337' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution from here didn't help

my middleware.js

module.exports = [
  'strapi::errors',
  'strapi::security',
  'strapi::poweredBy',
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      header: '*',
      origin: ['http://localhost:1337']
    }
  },
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];
2
  • What problem are you facing? If you're getting a CORS error message, add it to your question. Commented Mar 7, 2022 at 14:27
  • Note that the documentation for Strapi's CORS middleware mentions a headers (plural) property, but no header (singular) property. Commented Mar 7, 2022 at 14:28

1 Answer 1

40

I found the solution myself, maybe it will help someone

middlewares.js

module.exports = [
  'strapi::errors',
  'strapi::security',
  'strapi::poweredBy', // here
  {
    name: 'strapi::cors',
    config: {
      enabled: true, // deprecated in v4.25.8
      headers: '*',
      origin: ['http://localhost:1337', 'http://example2']
    }
  },
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];

Sign up to request clarification or add additional context in comments.

7 Comments

Note that in my case, strapi::cors was initially defined before strapi::poweredBy but it only works in exactly this order (cors must be after poweredBy not before).
not working any more with [email protected], also added @koa/cors - v5.0.0 as dependency & in resolution as well, still didn't work. I don't know why, this should be straight forward...
@dargmuesli I see, this has not been released yet right? because when i try to install [email protected], npm i throws error No matching version found for @strapi/[email protected]
Also, even if i add CORS like this in middlewares.js :- origin: env('CORS').split(','), still it doesn't work. I am still able to access strapi from localhost:3000 even though this is not in my CORS string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.