Vue3项目中axios请求后端接口

在Vue3项目中,我们可以使用axios库来发送HTTP请求。

安装axios

npm install axios

设置跨域

在vue3项目中找到vite.config.ts文件,我这里是http://192.168.16.90:8082为跨域路径,后面请求接口时,将"/api"加在接口路径前面就可实现跨域

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [
    vue(),
  ],
  base: '/', // 打包路径
  server: {
    port: 89, // 服务端口号
    open: false, // 服务启动时是否自动打开浏览器
    cors: true, // 允许跨域
    proxy: {
      '/api': {
        target: 'http://192.168.16.90:8082',//对面接口
        changeOrigin: true,
        rewrite: (path) => path.replace('/api', '')
      }
    }
  }
})

axios实例并配置基本设置

在src文件夹下创建utils文件夹,再创建request.ts,以下是request.ts文件里的代码示例:

/**axios封装* 请求拦截、相应拦截、错误统一处理*/
import axios from 'axios';
import router from '../router/index'
//  let protocol = window.location.protocol; //协议
//  let host = window.location.host; //主机
//  axios.defaults.baseURL = protocol + "//" + host;
export const apiName = "/api";
axios.defaults.baseURL = '/api'
axios.interceptors.request.use(
    //响应拦截
    async config => {
        // console.log(config)
        // 每次发送请求之前判断vuex中是否存在token        
        // 如果存在,则统一在http请求的header都加上token,这样后台根据token判断你的登录情况
        // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断 
        config.headers.token = sessionStorage.getItem('token')
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
// 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {return Promise.resolve(response); 
            //进行中
        } else {
            return Promise.reject(response); //失败
        }},// 服务器状态码不是200的情况    
        error => {
            if (error.response.status) {
                switch (error.response.status) {
                    // 401: 未登录                
                    // 未登录则跳转登录页面,并携带当前页面的路径                
                    // 在登录成功后返回当前页面,这一步需要在登录页操作。                
                    case 401:// 自定义过期之后的操作break// 403 token过期                
                    // 登录过期对用户进行提示                
                    // 清除本地token和清空vuex中token对象                
                    // 跳转登录页面                
                    console.log("跳转登录页面")
                    break
                    case 403:
                    sessionStorage.clear()
                    break// 404请求不存在                
                    case 404:break;// 其他错误,直接抛出错误提示                
                    default:
                }
                return Promise.reject(error.response);
            }
        }
);
/** * get方法,对应get请求 * @param {String} url [请求的url地址] * @param {Object} params [请求时携带的参数] */
const $get = (url: string, params: object) => {
    return axios.get(url, {params: params})
    .then(res => {
        return res.data;
    }).catch(err => {
        return err.data;
    })
}
/** * post方法,对应post请求 * @param {String} url [请求的url地址] * @param {Object} params [请求时携带的参数] */
const $post = (url: string, params: object) => {
    return axios.post(url, params,{headers:{'Content-Type': 'application/json'}}) 
    //是将对象 序列化成URL的形式,以&进行拼接   
    .then(res => {
        return res.data;
    })
    .catch(err => {
        return err.data
    })
}
//表单提交
const $postForm = (url: string, params: object) => {
    return axios.post(url, params,{headers:{'Content-Type': 'multipart/form-data'}}) 
    //是将对象 序列化成URL的形式,以&进行拼接   
    .then(res => {
        return res.data;
    })
    .catch(err => {
        return err.data
    })
}
const $delete = (url: string, params: object) => {
    return axios.delete(url, {params: params})
    .then(res => {
        return res.data;
    }).catch(err => {
        return err.data;
    })
}
const $put = (url: string, params: object) => {
    return axios.put(url, params)
    .then(res => {
        return res.data;
    }).catch(err => {
        return err.data;
    })
}
// 下面是将get和post方法挂载到vue原型上供全局使用、
// vue2.x中是通 Vue.prototype 来绑定的,像这样Vue.prototype.$toast = Toast。在vue3中取消了Vue.prototype,推荐使用globalProperties来绑定,
export default {
    install: (app: any) => {
        app.config.globalProperties['$put'] = $put;
        app.config.globalProperties['$delete'] = $delete;
        app.config.globalProperties['$get'] = $get;
        app.config.globalProperties['$post'] = $post;
        app.config.globalProperties['$postForm'] = $postForm;
        app.config.globalProperties['$axios'] = axios;
    }
}

main.ts文件里引入request

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

//引入router
import router from './router/index'
app.use(router)

//引入Axios
import http from './utils/request.ts'
app.use(http)

app.mount('#app')

使用接口

<template>
</template>

<script setup>
    import { getCurrentInstance } from "vue";
    const { proxy } = getCurrentInstance();
    proxy.$post("/index/login", data).then(res => {
        console.log(res )
    })
</script>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用Axios来在Vue 3和TypeScript调用后端接口。首先,确保你已经安装了Axios依赖,你可以通过运行以下命令来安装: ``` npm install axios ``` 接下来,在你的Vue组件,你可以导入Axios并使用它来发送HTTP请求。在你的脚本部分,添加以下行: ```typescript import axios from 'axios'; // ... axios.get('/api/endpoint') .then(response => { // 处理成功响应 }) .catch(error => { // 处理错误响应 }); ``` 这是一个简单的示例,使用了Axios的GET方法来发送一个请求到`/api/endpoint`。你可以根据需要使用其他HTTP方法,比如POST、PUT、DELETE等。 如果你需要在请求发送数据,你可以将数据作为第二个参数传递给Axios方法。例如,使用POST方法发送数据的示例: ```typescript axios.post('/api/endpoint', { data: 'example data' }) .then(response => { // 处理成功响应 }) .catch(error => { // 处理错误响应 }); ``` 这里的第二个参数是一个包含待发送数据的对象。 同时,你还可以为Axios添加全局配置,比如设置请求头或拦截器等。你可以在Vue应用的入口文件进行配置,例如在`main.ts`文件: ```typescript import { createApp } from 'vue'; import App from './App.vue'; import axios from 'axios'; // 设置基础URL axios.defaults.baseURL = 'https://api.example.com'; // 添加请求拦截器 axios.interceptors.request.use(config => { // 在发送请求之前做些什么 return config; }, error => { // 处理请求错误 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(response => { // 对响应数据做些什么 return response; }, error => { // 处理响应错误 return Promise.reject(error); }); createApp(App).mount('#app'); ``` 这里的示例设置了基础URL,并添加了请求和响应拦截器,你可以根据需要进行修改。 这就是使用AxiosVue 3和TypeScript调用后端接口的基本方法。你可以根据你的具体需求进一步扩展和优化代码。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈琦鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值