Last active
December 10, 2023 20:35
-
-
Save madkoding/442c3d0c8efb3be9d51fda92febaf5e7 to your computer and use it in GitHub Desktop.
Create proxy server for CORS issues (http-proxy package)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import required modules | |
const http = require("http"); | |
const httpProxy = require("http-proxy"); | |
// API target and proxy port configuration | |
const API_TARGET = 'https://pokeapi.co/api/v2/'; | |
const PROXY_PORT = 8080; | |
// Create a proxy server | |
const proxy = httpProxy.createProxyServer({}); | |
// Function to send error response | |
const sendError = (res, err) => { | |
console.error('Proxy error:', err); // Log the error for debugging | |
res.status(500).send({ | |
error: err.toString(), | |
message: "An error occurred in the proxy" | |
}); | |
}; | |
// Proxy error handling | |
proxy.on("error", (err, req, res) => { | |
sendError(res, err); | |
}); | |
// Function to enable CORS | |
const enableCors = (req, res) => { | |
if (req.headers['access-control-request-method']) { | |
res.setHeader('access-control-allow-methods', req.headers['access-control-request-method']); | |
} | |
if (req.headers['access-control-request-headers']) { | |
res.setHeader('access-control-allow-headers', req.headers['access-control-request-headers']); | |
} | |
if (req.headers.origin) { | |
res.setHeader('access-control-allow-origin', req.headers.origin); | |
res.setHeader('access-control-allow-credentials', 'true'); | |
} | |
}; | |
// Set header for CORS in proxy response | |
proxy.on("proxyRes", (proxyRes, req, res) => { | |
enableCors(req, res); | |
}); | |
// Create HTTP server and define request handling logic | |
const server = http.createServer((req, res) => { | |
// Handle OPTIONS method for CORS preflight | |
if (req.method === 'OPTIONS') { | |
enableCors(req, res); | |
res.writeHead(200); | |
res.end(); | |
return; | |
} | |
// Proxy the request to the API | |
proxy.web(req, res, { | |
target: API_TARGET, | |
secure: true, | |
changeOrigin: true | |
}, (err) => { | |
sendError(res, err); | |
}); | |
}); | |
// Start the server | |
server.listen(PROXY_PORT, () => { | |
console.log(`Proxy server listening on port ${PROXY_PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment