前端Vite+千问 实现简单AI对话功能

1、项目初始化与依赖安装

使用 Vue CLI/Vite 创建前端项目

注意:阿里云百炼的API不允许浏览器前端直接跨域调用,只能通过后端服务器转发

安装依赖:npm install express node-fetch cors

 

2. 获取阿里云百炼 API Key

注册并登录 :https://bailian.console.aliyun.com/

在【API-KEY管理】页面创建新的 API Key,复制保存

 

3. 编写本地代理服务器(解决CORS问题)

在项目根目录新建 proxy.js 文件,内容如下:

import express from 'express'
import fetch from 'node-fetch'
import cors from 'cors'

const app = express()
app.use(cors())
app.use(express.json())

const API_KEY = '你的百炼APIKey' // 替换为你自己的Key

app.post('/api/qwen', async (req, res) => {
  try {
    const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`,
      },
      body: JSON.stringify(req.body),
    })
    const data = await response.json()
    res.json(data)
  } catch (err) {
    res.status(500).json({ error: '代理请求失败' })
  }
})

app.listen(3001, () => {
  console.log('代理服务器已启动,端口 3001')
})

 

启动代理服务器:

node proxy.js

看到“代理服务器已启动,端口 3001”即为成功

 

4. 前端代码实现(新建chat.vue)

<template>
  <div class="chat-container">
    <div class="messages">
      <div v-for="(msg, idx) in messages" :key="idx" :class="msg.role">
        <strong>{{ msg.role === 'user' ? '你' : '千问' }}:</strong>{{ msg.content }}
      </div>
    </div>
    <form @submit.prevent="sendMessage" class="input-area">
      <input v-model="input" :disabled="isLoading" placeholder="请输入你的问题..." />
      <button type="submit" :disabled="isLoading || !input">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const messages = ref<{ role: 'user' | 'assistant', content: string }[]>([])
const input = ref('')
const isLoading = ref(false)

async function sendMessage() {
  if (!input.value.trim()) return
  messages.value.push({ role: 'user', content: input.value })
  isLoading.value = true
  try {
    const res = await fetch('http://localhost:3001/api/qwen', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: 'qwen-turbo',
        input: {
          messages: [
            { role: 'system', content: '你是一个AI助手' },
            ...messages.value.map(m => ({ role: m.role, content: m.content })),
          ]
        }
      }),
    })
    const data = await res.json()
    console.log('API返回:', data)
    const reply = data.output?.text || '千问未能理解你的问题'
    messages.value.push({ role: 'assistant', content: reply })
  } catch (e) {
    messages.value.push({ role: 'assistant', content: '请求失败' })
  }
  input.value = ''
  isLoading.value = false
}
</script>

<style scoped>
.chat-container { max-width: 500px; margin: 0 auto; }
.messages { min-height: 200px; margin-bottom: 1em; }
.user { text-align: right; color: #42b983; }
.assistant { text-align: left; color: #333; }
.input-area { display: flex; gap: 8px; }
input { flex: 1; }
</style>

 

5. 常见问题与排查

  • CORS 报错:只能通过本地代理服务器解决,不能直接前端请求百炼API
  • Invalid API-key provided:检查API Key是否为百炼平台生成、是否正确、是否有权限
  • 返回内容未显示:注意百炼API返回的内容字段为 data.output.text
  • 每次修改 .env 或代理代码后需重启服务

6. 运行流程

  1. 启动本地代理服务器:node proxy.js
  2. 启动前端项目:npm run dev
  3. 在页面输入问题,即可与“千问”对话

提示:这个功能适用于各大AI,替换key就可以尝试不同ai

很简单的一个小功能,与AI有个小接触,有问题欢迎留言~~~

posted @ 2026-01-29 17:32  danmo_xx  阅读(2)  评论(0)    收藏  举报