CORS (Cross-Origin Resource Sharing) — this is a mechanism that allows web pages to request resources from a different domain than the one the web page itself belongs to. A proxy server that adds CORS headers to the response allows bypassing restrictions associated with the same-origin policy.
Sometimes you may encounter a situation where you need to access resources that do not support CORS. In such cases, a proxy server can be used to add the necessary CORS headers to the responses, thereby bypassing the same-origin policy restrictions. This can be useful during development or when working with external APIs that, for some reason, do not include CORS support.
To set up your own CORS proxy server, you will need:
Create a subdomain, for example, cors.example.com. Issue and install SSL Let’s Encrypt for it. This step is optional; you can use the proxy without SSL, but then when requesting sites with SSL, you will receive a «mixed content» error.
npm install express cors-anywhere
const express = require('express');
const corsAnywhere = require('cors-anywhere');
// Create an instance of the proxy server
const proxy = corsAnywhere.createServer({
originWhitelist: [], // Allow all sources
requireHeader: [],
removeHeaders: []
});
// Create an instance of Express
const app = express();
// Use the proxy server at a specific path, for example, "/proxy"
app.use('/proxy', (req, res) => {
req.url = req.url.replace('/proxy/', '/'); // Strip '/proxy' from the URL
proxy.emit('request', req, res);
});
// Start the server
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(CORS Proxy running on port ${port});
});
node server.js
That’s it! Your own CORS proxy server is ready. To keep it running after closing the terminal, use the Tmux utility or other background work solutions.