How to bypass CORS without changing the original server and client?
sobes.tech AI
Answer from AI
It is impossible to bypass CORS without modifying the original server and client directly, as CORS policy is implemented by the browser for security reasons. However, there are several workarounds:
-
Proxy server: set up your own proxy server that makes requests to the original server and returns data to the client. The browser will communicate with your proxy instead of the original server, and CORS will not block the request.
-
JSONP: if the server supports JSONP, you can use this mechanism, which is not subject to CORS, but it is an outdated and limited method.
-
Browser extensions: during development, you can use extensions that disable CORS, but this is not suitable for production.
-
Using iframe and postMessage: a complex option that requires control over another domain.
Example of a proxy in Node.js using express and http-proxy-middleware:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api', createProxyMiddleware({
target: 'https://original-server.com',
changeOrigin: true,
pathRewrite: { '^/api': '' },
}));
app.listen(3000);
The client will make requests to http://localhost:3000/api/..., and the proxy will redirect them to the original server, bypassing CORS.