zaiwen2 / index.js
yuoop's picture
Update index.js
82465f0 verified
// Import required packages
import express from 'express';
import cors from 'cors';
import fetch from 'node-fetch';
const app = express();
const PORT = process.env.PORT || 7860;
// Target server
const TARGET_DOMAIN = "https://aliyun.zaiwen.top";
// Middleware setup
app.use(express.json());
app.use(cors({
origin: '*',
methods: ['POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// Only allow POST requests
app.all('*', (req, res, next) => {
if (req.method !== 'POST') {
return res.status(405).send('Method Not Allowed');
}
next();
});
// Proxy handler
app.post('*', async (req, res) => {
const targetUrl = `${TARGET_DOMAIN}${req.path}${req.url.includes('?') ? '?' + req.url.split('?')[1] : ''}`;
try {
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...req.headers
},
body: JSON.stringify(req.body)
});
const body = await response.text(); // 保持原样,前端自己决定如何解析
res.status(response.status);
// 把目标服务器返回的 headers 也加回来(注意 CORS 要处理一下)
response.headers.forEach((value, key) => {
if (key.toLowerCase() === 'content-length') return; // 不转发 content-length
res.setHeader(key, value);
});
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
return res.send(body);
} catch (error) {
console.error('Proxy Error:', error);
return res.status(500).send('Proxy Server Error');
}
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// For Huggingface deployment
export default app;