Last active
March 15, 2022 10:26
-
-
Save HabaCo/ca67b40a2363522b4af0d77117f0d46a to your computer and use it in GitHub Desktop.
A simply proxy-server can handle web-based request across CORS (easy run with node js)
This file contains 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 cors = require('cors'); | |
const bodyParser = require('body-parser'); | |
const request = require('request'); | |
const port = 8088; | |
const app = express(); | |
app.use(cors()) | |
app.use(bodyParser.urlencoded({ extended: true })); | |
function requestDirect(req, res) { | |
// add header with key "Host-Redirect" to tell proxy redirect to host | |
let redirectUrl = req.header('Host-Redirect'); | |
let url = redirectUrl + req.originalUrl; | |
request( | |
{ | |
method: req.method, | |
uri: url, | |
form: req.body | |
} | |
, function (error, response, body) { | |
try { | |
res.status(response.statusCode); | |
res.end(body); | |
} catch (e) { | |
res.status(500) | |
res.end(error.stack) | |
} | |
} | |
) | |
} | |
app.use(function (req, res, next) { | |
// handle request url | |
requestDirect(req, res); | |
}); | |
app.listen(port); | |
console.log('Listening at http://localhost:' + port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment