From 0c645b3800a80e5feda3e31dac28eadb7fc3ace6 Mon Sep 17 00:00:00 2001 From: "zhangkun9038@dingtalk.com" Date: Mon, 17 Mar 2025 10:09:54 +0800 Subject: [PATCH] first add --- package.json | 15 +++++++++ public/index.html | 77 +++++++++++++++++++++++++++++++++++++++++++++++ server.js | 55 +++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+) create mode 100644 package.json create mode 100644 public/index.html create mode 100644 server.js diff --git a/package.json b/package.json new file mode 100644 index 0000000..c6ea2fb --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "chat-api", + "version": "1.0.0", + "description": "Chat API with Node.js", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.18.2", + "axios": "^1.6.2", + "cors": "^2.8.5" + } +} + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..51c42ca --- /dev/null +++ b/public/index.html @@ -0,0 +1,77 @@ + + + + + + Chat API + + + +
+

Chat with AI

+ + +
+
+ + + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..3fd78c7 --- /dev/null +++ b/server.js @@ -0,0 +1,55 @@ +const express = require('express'); +const axios = require('axios'); +const cors = require('cors'); +const path = require('path'); + +const app = express(); +const PORT = 3000; + +// 中间件 +app.use(cors()); +app.use(express.json()); +app.use(express.static(path.join(__dirname, 'public'))); + +// API路由 +app.post('/api/chat', async (req, res) => { + try { + const userMessage = req.body.message; + + const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', { + model: "farui-plus", + input: { + messages: [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: userMessage } + ] + } + }, { + headers: { + 'Authorization': `Bearer YOUR_API_KEY`, + 'Content-Type': 'application/json' + } + }); + + res.json({ + status: 'success', + response: response.data + }); + } catch (error) { + console.error(error); + res.status(500).json({ + status: 'error', + message: 'Internal server error' + }); + } +}); + +// 前端路由 +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, 'public', 'index.html')); +}); + +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`); +}); +