No articles found
Try different keywords or browse our categories
Fix: Cross-origin request blocked in Vite dev server error
Quick fix for 'Cross-origin request blocked in Vite dev server' error. Learn how to configure CORS and proxy settings in Vite.
The ‘Cross-origin request blocked in Vite dev server’ error occurs when your Vite development server makes requests to external APIs or different ports that are blocked by CORS policies.
How the Error Happens
❌ Error Scenario:
// ❌ This causes CORS error in dev server
fetch('http://localhost:8000/api/data') // ❌ Different port - CORS blocked
// Error: Cross-origin request blocked
✅ Quick Fix - Configure Vite CORS and Proxy
Solution 1: Configure Proxy in Vite
// ✅ In vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:8000', // ✅ Your backend server
changeOrigin: true,
secure: false,
},
},
},
});
// ✅ Now this works in dev
fetch('/api/data') // ✅ Proxied to http://localhost:8000/api/data
Solution 2: Enable CORS in Dev Server
// ✅ In vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
server: {
cors: {
origin: "*", // ✅ Allow all origins in dev (not for production!)
credentials: true
}
}
});
Solution 3: Specific Proxy Configuration
// ✅ Advanced proxy configuration
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
headers: {
'X-Forwarded-Host': 'localhost:5173'
}
}
}
}
});
Solution 4: Backend CORS Configuration
// ✅ If you control the backend, enable CORS
// For Express.js backend
app.use(cors({
origin: 'http://localhost:5173', // ✅ Vite dev server origin
credentials: true
})); Related Articles
Fix: Error when starting dev server: port already in use error
Quick fix for 'Error when starting dev server: port already in use' error. Learn how to resolve port conflicts in JavaScript development servers.
Fix: Failed to resolve entry for package.json error
Quick fix for 'Failed to resolve entry for package.json' error. Learn how to resolve module resolution issues in Vite, Rollup, and other JavaScript bundlers.
Fix: Vite preview not working error
Quick fix for 'Vite preview not working' error. Learn how to resolve issues with Vite's preview server for production builds.