You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Strapi v4对接Vue.js时遭遇CORS异常,请求正确配置CORS中间件的方法

Fixing CORS Error with Strapi v4 and Vue.js

Hey there! Let's work through that CORS issue you're facing. The error message you got is super specific—when your request includes credentials (like cookies or auth headers), Strapi can't use the wildcard * for Access-Control-Allow-Origin; it needs an explicit domain. Here's how to fix this properly without crashing your CMS:

Step 1: Locate/Create the Middlewares Config File

In Strapi v4, CORS settings are managed in the config/middlewares.js file at the root of your project. If this file doesn't exist, go ahead and create it.

Step 2: Add the Correct CORS Configuration

Replace the default CORS middleware entry with a custom one that specifies your Vue app's origin and enables credentials. Make sure you keep all other required Strapi middlewares intact—this is probably why your CMS crashed earlier (missing other essential middlewares!).

Here's a complete, working middlewares.js example:

module.exports = [
  'strapi::errors',
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'http://localhost:8080'],
        },
      },
    },
  },
  {
    resolve: 'strapi::cors',
    config: {
      origin: 'http://localhost:8080', // Your Vue app's URL
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
      credentials: true, // Critical for requests with credentials
    },
  },
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];

Key Notes:

  • credentials: true: This tells Strapi to allow credentials in requests, which matches your Vue app's withCredentials setting.
  • Keep all other middlewares: Removing entries like strapi::body or strapi::query will break core Strapi functionality—so don't skip those!
  • Multiple origins? If you need to allow multiple frontend domains, use an array:
    origin: ['http://localhost:8080', 'https://your-production-app.com']
    

Step 3: Verify Your Vue Request

Make sure your Vue app's HTTP request includes the withCredentials flag. For example, if you're using Axios:

import axios from 'axios';

async fetchCategories() {
  try {
    const response = await axios.get('http://localhost:1337/api/categories', {
      withCredentials: true // Match this to Strapi's credentials setting
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

Step 4: Restart Strapi

After saving the middlewares.js file, restart your Strapi server to apply the changes. This ensures the new CORS settings take effect.

That should resolve the CORS error while keeping your CMS running smoothly. Let me know if you run into any other issues!

内容的提问来源于stack exchange,提问作者Refilon

火山引擎 最新活动