JAVASCRIPT
Bypassing CORS with a Server-Side API Proxy
Set up a simple Node.js server-side proxy using Express.js to securely fetch data from third-party APIs, effectively bypassing client-side Cross-Origin Resource Sharing (CORS) restrictions.
const express = require('express');
const axios = require('axios'); // Or node-fetch, or any HTTP client library
const cors = require('cors'); // For allowing client requests to YOUR proxy
const app = express();
const PORT = process.env.PORT || 3001;
// Enable CORS for your client application to access this proxy
// In production, configure this more strictly, e.g., `origin: 'https://your-frontend-domain.com'`
app.use(cors());
// Middleware to parse JSON request bodies
app.use(express.json());
// Define a proxy endpoint for a specific external API
// Example: Proxying requests to a public API like JSONPlaceholder
app.get('/api/proxy/jsonplaceholder/:resource', async (req, res) => {
const { resource } = req.params; // e.g., 'posts', 'users'
const externalApiUrl = `https://jsonplaceholder.typicode.com/${resource}`;
try {
const response = await axios.get(externalApiUrl, { params: req.query });
res.status(response.status).json(response.data);
} catch (error) {
console.error(`Error proxying request to ${externalApiUrl}:`, error.message);
res.status(error.response?.status || 500).json({ error: 'Failed to fetch data from external API.' });
}
});
// Example for a POST request proxy
app.post('/api/proxy/my-external-service/:endpoint', async (req, res) => {
const { endpoint } = req.params;
const externalApiUrl = `https://api.myexternalservice.com/${endpoint}`;
const requestBody = req.body;
try {
const response = await axios.post(externalApiUrl, requestBody, {
// Optionally forward headers from client if needed, e.g., Authorization
// headers: { 'X-Custom-Header': req.headers['x-custom-header'] }
});
res.status(response.status).json(response.data);
} catch (error) {
console.error(`Error proxying POST request to ${externalApiUrl}:`, error.message);
res.status(error.response?.status || 500).json({ error: 'Failed to post data to external API.' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});
// --- Client-Side Usage Example ---
/*
// Assuming your proxy server is running on http://localhost:3001
async function fetchPostsFromProxy() {
try {
const response = await fetch('http://localhost:3001/api/proxy/jsonplaceholder/posts');
const data = await response.json();
console.log('Posts fetched via proxy:', data);
} catch (error) {
console.error('Error fetching posts via proxy:', error);
}
}
// (async () => {
// await fetchPostsFromProxy();
// })();
*/
How it works: Cross-Origin Resource Sharing (CORS) policies often prevent client-side JavaScript from directly making requests to third-party APIs on different domains. This Node.js snippet demonstrates how to create a simple server-side proxy using Express.js to bypass these restrictions. Your client-side application makes requests to your *own* backend proxy endpoint (e.g., `/api/proxy/jsonplaceholder/posts`), which then securely forwards these requests to the actual external API. Since the server-to-server request is not subject to browser CORS policies, the data is fetched successfully and then returned to your client. This also allows you to hide API keys, perform rate limiting, or transform data before sending it to the client.