1. 首先,安装 Axios:
npm install axios
2. 在 src 目录下创建一个 api 文件夹,然后创建 http.js 文件:
// src/api/http.js
import axios from 'axios'const http = axios.create({
baseURL: 'http://61.149.87.142:3000', // 使用您的服务器 IP 和端口
timeout: 10000, // 请求超时时间
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
http.interceptors.request.use(
config => {
// 在发送请求之前做些什么,例如加入 token
// config.headers['Authorization'] = 'Bearer ' + token
return config
},
error => {
// 对请求错误做些什么
return Promise.reject(error)
}
)// 响应拦截器
http.interceptors.response.use(
response => {
// 对响应数据做点什么
return response.data
},
error => {
// 对响应错误做点什么
return Promise.reject(error)
}
)export default http
3. 创建 api.js 文件来定义具体的 API 请求:
// src/api/api.js
import http from './http'export const sendMessage = (message) => {
return http.post('/chat', { message })
}
4. 在 Vue 组件中使用:
<script setup>
import { ref } from 'vue'
import { sendMessage } from '@/api/api'const message = ref('')
const response = ref('')const handleSendMessage = async () => {
try {
const result = await sendMessage(message.value)
response.value = result.response
} catch (error) {
console.error('Error sending message:', error)
}
}
</script><template>
<input v-model="message" placeholder="输入消息" />
<button @click="handleSendMessage">发送</button>
<p>回复: {{ response }}</p>
</template>
5. 在 main.js 中全局配置(可选):
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import http from './api/http'const app = createApp(App)
app.config.globalProperties.$http = http
app.mount('#app')