proxy / index.js
hf-bmfy's picture
Create index.js
03d9585 verified
raw
history blame
1.2 kB
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors')
const PORT = 7860;
const API_CONFIG = JSON.parse(process.env.API_CONFIG || "{}")
const app = express();
app.use(cors())
function formatValue(value) {
let result = value
if (typeof result === 'string') {
result = {
target: value
}
}
return result
}
for (const [path, value] of Object.entries(API_CONFIG)) {
const format = formatValue(value)
const apiProxy = createProxyMiddleware(path, {
target: format.target,
changeOrigin: true,
pathRewrite: {
[`^${path}`]: '',
},
onProxyReq: (proxyReq, req, res) => {
console.log(format);
if (format.auth || format.auth == '') {
proxyReq.setHeader('authorization', 'Bearer ' + format.auth)
}
},
onProxyRes: (proxyRes, req, res) => {
if (req.originalUrl === path || req.originalUrl === path + '/') {
res.json({
code: 200,
details: 'success',
});
}
},
});
app.use(path, apiProxy);
}
app.listen(PORT, () => {
console.log(`Service running successfully http://localhost:${PORT}`);
});