Last active
February 17, 2021 21:20
-
-
Save sashaaro/2ce5c5b4909978a1e9583fa3c6ba81f1 to your computer and use it in GitHub Desktop.
simple onefile nodejs proxy for backend and frontend
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
const http = require('http') | |
const frontendPort = 4200; // typically angular | |
const backendPort = 3001; | |
const backendRoutePrefix = '/api' | |
const server = http.createServer((request, response) => { | |
console.log('Request: ' + request.url) | |
const isApi = request.url.startsWith(backendRoutePrefix); | |
const options = { | |
hostname: 'localhost', | |
port: isApi ? backendPort : frontendPort, | |
path: request.url, | |
method: request.method, | |
headers: request.headers, | |
}; | |
const proxy = http.request(options, (res) => { | |
response.writeHead(res.statusCode, res.headers); | |
res.pipe(response, { | |
end: true | |
}); | |
}); | |
proxy.on('error', error => { | |
console.log('Error', error.code); | |
response.destroy(error); | |
}) | |
proxy.on('abort', error => { | |
response.destroy(error); | |
}) | |
if (proxy.writable) { | |
request.pipe(proxy, { | |
end: true | |
}); | |
} | |
request.on('error', error => { | |
console.log('Error', error) | |
response.end(); | |
}) | |
}); | |
server.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment