在 Strapi 4 中设置 Cors

Woc*_*eez 7 javascript localhost cors strapi

我使用 Strapi 4 作为本地主机,当我通过 url 添加新资产时,cors 设置出现问题

图片上传出现CORS错误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.

这里的解决方案没有帮助

我的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',
];
Run Code Online (Sandbox Code Playgroud)

Woc*_*eez 36

我自己找到了解决方案,也许会对某人有所帮助

middlewares.js

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

Run Code Online (Sandbox Code Playgroud)

  • 请注意,在我的例子中,“strapi::cors”最初是在“strapi::poweredBy”之前定义的,但它只能按照这个顺序工作(cors 必须在poweredBy 之后而不是之前)。 (6认同)