feat: 添加后端接口
parent
50c9288802
commit
d796e10ec6
@ -0,0 +1,3 @@
|
||||
OPENAI_API_KEY=''
|
||||
|
||||
VITE_GLOB_API_URL='http://192.168.110.170:3002'
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,41 @@
|
||||
import dotenv from 'dotenv'
|
||||
import { ChatGPTAPI } from 'chatgpt'
|
||||
import express from 'express'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const app = express()
|
||||
|
||||
app.use(express.json())
|
||||
|
||||
async function chatAPI(message: string) {
|
||||
if (!message)
|
||||
throw new Error('Message is not defined')
|
||||
|
||||
if (!process.env.OPENAI_API_KEY)
|
||||
throw new Error('OPENAI_API_KEY is not defined in .env file')
|
||||
|
||||
try {
|
||||
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
|
||||
const res = await api.sendMessage(message)
|
||||
return res
|
||||
}
|
||||
catch (error) {
|
||||
return error
|
||||
}
|
||||
}
|
||||
|
||||
app.all('*', (req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
next()
|
||||
})
|
||||
|
||||
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
|
||||
|
||||
app.post('/chat', async (req, res) => {
|
||||
const { message } = req.body
|
||||
const response = await chatAPI(message)
|
||||
res.send(response)
|
||||
})
|
@ -0,0 +1,4 @@
|
||||
interface ImportMetaEnv {
|
||||
/** api url */
|
||||
readonly VITE_GLOB_API_URL: string;
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
import axios from 'axios'
|
||||
|
||||
async function fetchChatAPI(message: string) {
|
||||
if (!message || message.trim() === '')
|
||||
return Promise.reject(new Error('Message is empty'))
|
||||
|
||||
try {
|
||||
const { status, data } = await axios.post(
|
||||
'http://192.168.110.170:3002/chat',
|
||||
{ message },
|
||||
)
|
||||
|
||||
if (status === 200) {
|
||||
if (data.text)
|
||||
return Promise.resolve(data)
|
||||
else if (data.statusText)
|
||||
return Promise.reject(new Error(data.statusText))
|
||||
}
|
||||
|
||||
return Promise.reject(new Error('Request failed'))
|
||||
}
|
||||
catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
export { fetchChatAPI }
|
Loading…
Reference in New Issue