Spaces:
Running
Running
const express = require('express'); | |
const proxy = require('express-http-proxy'); | |
const app = express(); | |
const targetUrl = 'https://api.openai.com'; // OpenAI API endpoint | |
const openai_key = process.env.OPENAI_KEY; | |
if (!openai_key) { | |
console.error('Error: OPENAI_KEY is not set.'); | |
process.exit(1); | |
} | |
app.use('/', proxy(targetUrl, { | |
proxyReqOptDecorator: (proxyReqOpts, srcReq) => { | |
// Modify the request headers if necessary | |
proxyReqOpts.headers['Authorization'] = 'Bearer ' + openai_key; | |
console.log('Proxy request options:', proxyReqOpts); | |
return proxyReqOpts; | |
}, | |
userResDecorator: (proxyRes, proxyResData, userReq, userRes) => { | |
console.log('Proxy response status:', proxyRes.statusCode); | |
console.log('Proxy response data:', proxyResData.toString('utf8')); | |
return proxyResData; | |
}, | |
proxyErrorHandler: (err, res, next) => { | |
console.error('Proxy error:', err); | |
res.status(500).send('Proxy error'); | |
} | |
})); | |
const port = 7860; | |
app.listen(port, () => { | |
console.log(`Reverse proxy server listening on port ${port}`); | |
}); |