Last active
April 1, 2022 06:37
-
-
Save isabolic/38fbbc54c105b0db4dc05fab0cc61297 to your computer and use it in GitHub Desktop.
nodejs proxy example
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 express = require('express'); | |
| const morgan = require("morgan"); | |
| const cors = require('cors'); | |
| const { createProxyMiddleware } = require('http-proxy-middleware'); | |
| // Create Express Server | |
| const app = express(); | |
| // cors | |
| app.use(cors()) | |
| // Logging | |
| app.use(morgan('dev')); | |
| // Configuration | |
| const PORT = 5000; | |
| const HOST = "localhost"; | |
| const API_SERVICE_URL = "https://api-test.aws.machine"; | |
| // Proxy endpoints | |
| app.use('/api', createProxyMiddleware({ | |
| target: API_SERVICE_URL, | |
| changeOrigin: true, | |
| onProxyRes: (proxyRes, req, res) => { | |
| // log original request and proxied request info | |
| const exchange = `[${req.method}] [${proxyRes.statusCode}] ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path}`; | |
| console.log(exchange); // [GET] [200] / -> http://www.example.com | |
| }, | |
| })); | |
| // Start the Proxy | |
| app.listen(PORT, HOST, () => { | |
| console.log(`Starting Proxy at ${HOST}:${PORT}`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment