VUE3中运用axios处理后端数据

(1)在src下新建一个http文件夹,文件夹下新建一个index.js

(2)在index.js文件中引入axios

(3)在index.js里面写axios实例和拦截器

具体内容:

import axios from 'axios'

// 创建一个 axios 实例

const service = axios.create({

baseURL: 'https://service-c281p5uq-1306002440.hk.apigw.tencentcs.com', // 所有的请求地址前缀部分

timeout: 60000, // 请求超时时间毫秒

// withCredentials: true, // 异步请求携带cookie

headers: {

// 设置后端需要的传参类型

'Content-Type': 'application/json',

// 'token': 'your token',

'X-Requested-With': 'XMLHttpRequest',

},

})

// 添加请求拦截器

service.interceptors.request.use(

function (config) {

// 在发送请求之前做些什么

return config

},

function (error) {

// 对请求错误做些什么

// console.log(error)

return Promise.reject(error)

}

)

// 添加响应拦截器

service.interceptors.response.use(

function (response) {

// 对响应数据做点什么

return response;

},

function (error) {

// 对响应错误做点什么

return Promise.reject(error);

}

)

export default service

(4)又在src目录下新建一个文件夹apis,文件夹里面新建一个index.js文件

这里面是写具体的请求方法,引入之前在http文件夹下的index.js文件

具体内容:

import API from '../http/index'

/* banner(轮播图)数据 */

function postBanner(type1) {

return API.post(`/banner?type=${type1}`).then((res) => {

return res.data.banners;

})

}

/* 二维码key生成接口 */

function getErWeiMaKey() {

return API.get(`/login/qr/key?timerstamp=${Date.now()}`)

}

/* 二维码生成接口 */

function getErWeiMa(key) {

return API.get(`/login/qr/create?key=${key}&qrimg=true&timerstamp=${Date.now()}`)

}

/* 二维码登录状态 */

function getErWeiMaStatus(key) {

// console.log(key)

return API.get(`/login/qr/check?key=${key}&qrimg=true&timerstamp=${Date.now()}`)

}

/* 用户登录状态 */

function loginStatus() {

return API.post(`/login/status?timerstamp=${Date.now()}`).then((res) => {

return res.data

})

}

/* 退出登陆 */

function logout() {

return API.get('/logout').then((res) => {

return res.data

})

}

export { postBanner, getErWeiMaKey, getErWeiMa, getErWeiMaStatus, loginStatus }

(5)在vue页面中引入需要的方法

猜你喜欢

转载自blog.csdn.net/Yang_Ming_Lei/article/details/129770473