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
| // Install node-http-proxy package first | |
| var http = require("http"), httpProxy = require("http-proxy"); | |
| var API_TARGET = 'https://pokeapi.co/api/v2/' | |
| var PROXY_PORT = 8080 | |
| // Create a proxy server with custom application logic | |
| var proxy = httpProxy.createProxyServer({}); | |
| var sendError = function(res, err) { | |
| return res.status(500).send({ | |
| error: err, | |
| message: "An error occured in the proxy" | |
| }); | |
| }; | |
| // error handling | |
| proxy.on("error", function (err, req, res) { | |
| sendError(res, err); | |
| }); | |
| var enableCors = function(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 | |
| proxy.on("proxyRes", function(proxyRes, req, res) { | |
| enableCors(req, res); | |
| }); | |
| var server = http.createServer(function(req, res) { | |
| // You can define here your custom logic to handle the request | |
| // and then proxy the request. | |
| if (req.method === 'OPTIONS') { | |
| enableCors(req, res); | |
| res.writeHead(200); | |
| res.end(); | |
| return; | |
| } | |
| proxy.web(req, res, { | |
| target: API_TARGET, | |
| secure: true, | |
| changeOrigin: true | |
| }, function(err) { | |
| sendError(res, err); | |
| }); | |
| }); | |
| server.listen(PROXY_PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment