- Install the
cors
package using npm:
npm install cors
- Import the
cors
package in your Vue.js application:
// In your Vue.js file (e.g., main.js)
import cors from 'cors'
- Use the
cors
middleware in your Express.js server:
// In your Express.js server file (e.g., server.js)
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// Your other middleware and route handling here
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Configure CORS options if needed:
// In your Express.js server file (e.g., server.js)
const corsOptions = {
origin: 'http://example.com', // Replace with your allowed origin
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
optionsSuccessStatus: 204,
};
// Enable CORS with options
app.use(cors(corsOptions));
- Allow specific routes to bypass CORS:
// In your Express.js server file (e.g., server.js)
const corsOptions = {
origin: 'http://example.com', // Replace with your allowed origin
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
optionsSuccessStatus: 204,
};
// Enable CORS with options for specific routes
app.use('/api/specific-route', cors(corsOptions));
// Your other middleware and route handling here
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});