Vue 3 中配置网络请求的方法,使用 Axios 作为 HTTP 客户端

 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')

这样配置后,您可以在任何组件中使用 this.$http 来发起网络请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值