-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (37 loc) · 1.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const PORT = process.env.PORT || 3000;
const fetch = require('node-fetch');
const express = require("express");
const app = express();
const API_HOST = 'https://api.openai.com';
app.use(express.json());
app.post("/api/*", async (request, response) => {
//拼接 OpenAI API 转发地址
const url = API_HOST + request.url.substring(4);
//读取 req 中的 Authorization,存放在 authKey 中
const authKey = request.header("Authorization");
if (!authKey) return new Response("Not allowed", { status: 403 });
//读取 req 中的 body, 存放在 body 中
const body = request.body;
try {
let result = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': authKey
},
body: JSON.stringify(body),
});
const resultJSON = await result.json();
response.set({
"Content-Type": "application/json",
"Cross-Origin-Resource-Policy": "Cross-Origin",
"Access-Control-Allow-Origin": "*"
})
response.status(result.status).send(resultJSON);
} catch {
response.status(500).json({ error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});