vue 版本
vue3
安装依赖
安装 axios
npm i axiso --save-dev
封装
这里将封装到http.js 引入axios 创建axios(设置url地址,访问前缀,超时时间) 然后设置拦截器(成功响应拦截,失败拦截器) 成功拦截器可以做是否登录的统一处理(前提是未登录返回的也是200系列状态码,不是的话走到失败拦截器中)
import axios from "axios"
export default function createHttp() {
const http = axios.create({
url: 'http:localhost:8080',
baseURL: 'api',
timeout: 6000,
})
http.interceptors.response.use(
(response) => {
return response.data;
}, (response) => {
console.log(response)
})
return http;
}
挂载到vue上去
因为以前用vue2都是通过this.$axios调用axios 这里和以前保持一致吧 vue3 需要通过 config.globalProperties 挂载
import {createApp} from 'vue'
import App from './App.vue'
import {createWebHistory} from 'vue-router'
import createRouter from "./router"
import createHttp from "@/http";
const router = createRouter(createWebHistory())
const vueApp = createApp(App)
vueApp.config.globalProperties.$axios = createHttp()
vueApp.use(router).mount('#app')
简单使用
<template>
<common-header></common-header>
<router-view></router-view>
</template>
<script>
import CommonHeader from "../components/CommonHeader";
export default {
name: "HomePage",
components: {CommonHeader},
mounted() {
this.$axios.get('https://www.baidu.com').then((response)=>{
console.log(response)
})
}
}
</script>
开发环境下的跨域问题
上面的访问https://www.baidu.com的示例 拿不到数据,这是因为跨域了 开发环境下解决跨域设置node代理即可 设置vue.config.js 中配置代理相关信息
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: true,
devServer: {
host: 'localhost',
port: 8080,
proxy: {
'/api': {
target: 'https://www.baidu.com',
pathRewrite: {
'/api': '/'
},
},
}
},
})
测试
<template>
<common-header></common-header>
<router-view></router-view>
</template>
<script>
import CommonHeader from "../components/CommonHeader";
export default {
name: "HomePage",
components: {CommonHeader},
data() {
return {
content: 22,
}
},
mounted() {
this.$axios.get('/').then((response) => {
console.log(response)
})
}
}
</script>
|