The CORS error occurs because the CDN (unpkg.com) doesn't include the Access-Control-Allow-Origin header in its responses, blocking cross-origin requests from your domain (https://wlt.design). Here are the most effective solutions:
Recommended Fixes
1. Use a Proxy Server
Create a middleware server to forward requests to unpkg.com and add CORS headers. This bypasses the CDN's restrictions.
Node.js Proxy Example (Express):
const express = require('express');
const axios = require('axios');
const app = express();
// Add CORS headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
// Proxy route
app.get('/proxy/:path', async (req, res) => {
const path = req.params.path;
const response = await axios.get(`https://unpkg.com/${path}`);
res.send(response.data);
});
app.listen(3000, () => {
console.log('Proxy server running on port 3000');
});
Usage: Replace the CDN URL with your proxy endpoint:
<script src="http://localhost:3000/proxy/three@0.159.0/build/three.module.min.js"></script>
2. Host the File Locally
Download the Three.js file and serve it from your domain to eliminate cross-origin issues entirely.
Steps:
- Download
three.module.min.js from unpkg.com.
- Place it in your project’s
js directory.
- Update your script tag:
<script src="/js/three.module.min.js"></script>
3. Test Alternative CDNs
Check if CDNs like jsDelivr allow CORS. For example:
<script src="https://cdn.jsdelivr.net/npm/three@0.159.0/build/three.module.min.js"></script>
Verify via browser tools whether the response includes Access-Control-Allow-Origin: *[1][4].
Why This Happens
- CORS Policy: Browsers block cross-origin requests unless the server explicitly allows them via headers[1][4].
- CDN Restrictions: Many CDNs (e.g., unpkg.com) omit CORS headers, triggering errors[4][8].
Temporary Workarounds (Development Only)
- Browser Extensions: Tools like CORS Unblock can bypass restrictions locally[4].
- Disable CORS in Chrome: Use
--disable-web-security flag (insecure for production)[10][11].
Best Practice
For production, host the file locally or use a proxy server to maintain control over CORS headers. Avoid relying on CDN CORS policies, as they can change unexpectedly[4][8].