axios使用
普通使用、vue2项目:封装axios请求以及把token放在header里面、vue3项目:封装axios请求
·
Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中
安装:
npm install axios
普通使用:
main.js中引用:
import axios from 'axios'
Vue.prototype.$axios = axios
在页面上使用:
this.$axios.post('https://xxxx.xxxxx.cn/api/user/login', {username: "admin",
password: "admin"}).then(res => {
if (res.data.code === 200) {
console.log('请求成功!', res)
} else {
console.log('请求失败!', res.data.message);
}
})
封装axios
request.js
import axios from 'axios';
const httpRequest = function(query) {
return new Promise((resolve, reject) => {
axios({
url: query.url,
method: query.method ? query.method : 'get',
headers: {
'token': token,
},
data: query.data
}).then(({ data: res }) => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}
export default httpRequest
main.js
import httpRequest from "./request/request";
Vue.prototype.$axios = httpRequest;
使用:
this.$axios({
url: `https://xxx.xxx.xxx`,
}).then((res) => {
if (res.code != 0) {
this.$message.error(res.message)
return
}
})
vue2项目:封装axios请求以及把token放在header里面
//auth.js 页面
//获取token
export function getToken(){
return localStorage.getItem("token")
}
//设置token
export function setToken(token){
return localStorage.setItem("token",token)
}
//删除token
export function removeToken(){
return localStorage.removeItem("token")
}
//http.js页面
import service from './service.js'
export function get(url,params){
const config = {
method:"get",
url:url,
}
if(params){config.params=params}
return service(config)
}
export function post(url,params){
const config = {
method:"post",
url:url,
}
if(params){config.data=params}
return service(config)
}
//service.js页面
import axios from 'axios'
import { getToken, removeToken } from "./auth.js";
import router from '@/router/index.js';
import { Message } from 'element-ui';
var service = axios.create({
baseURL: 'https://xxxx.xxxxx.com', //请求头
timeout: 5000
})
/**
* 请求拦截
*/
service.interceptors.request.use(config => {
config.headers['token'] = getToken('token') // 请求头带上token
return config
}, error => {
return Promise.reject(error)
})
/**
* 响应拦截
*/
service.interceptors.response.use(response => {
if (response.data == null) {
return response;
}
if (response.data.code == -2) { //token失效
removeToken()
router.push({ name: 'login' })
return response;
}
if (response.data.code == !0) {
Message.error(response.data.msg)
return Promise.reject(response.data.msg);
}
return response.data
}, error => {
return Promise.reject(error)
})
export default service
登录页面发起登录请求:
import { setToken } from "@/request/auth.js";
import { post, get } from "@/request/http.js";
//登录
dataFormSubmit() {
this.$refs["dataForm"].validate((valid) => {
if (valid) {
post("/xxxxxx/user/login", this.dataForm).then(res => {
if (res && res.code === 0) {
setTimeout(this.$router.push("/vueLayout"), 2000);
setToken(res.token); //获取token
} else {
this.$message.error(res.msg);
}
}).catch(() => { });
}
});
},
登录成功跳转的页面:这时候的token已经在header里了
import { post, get } from "@/request/http.js";
userinfo() {
get("/xxxxx/user/info").then((res) => {
});
},
vue3项目:封装axios请求
在src文件夹下面新建一个plugins文件夹,里面放一个axiosInstance.js文件
//导入axios
import axios from 'axios'
import router from '@/router/index.js';
import {
getToken,
removeToken
} from "./auth.js";
//创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_SERVER_API,
timeout: 2000
})
/**
* 请求拦截
*/
service.interceptors.request.use(config => {
config.headers['token'] = getToken('token')
return config
}, error => {
return Promise.reject(error)
})
/**
* 响应拦截
*/
service.interceptors.response.use(response => {
if (response.data == null) {
return response;
}
if (response.data.code == -2) {
removeToken()
router.push({
name: 'myLogin'
})
return response;
}
return response.data
}, error => {
return Promise.reject(error)
})
export default service
auth.js文件:
//获取token
export function getToken(){
return localStorage.getItem("token")
}
//设置token
export function setToken(token){
return localStorage.setItem("token",token)
}
//删除token
export function removeToken(){
return localStorage.removeItem("token")
}
在main.js引用:
import axios from '@/plugins/axiosInstance.js'
app.config.globalProperties.$axios = axios;
console.log('环境:' + process.env.VUE_APP_ENV);
console.log('api:' + process.env.VUE_APP_SERVER_API);
.env.dev
VUE_APP_SERVER_API="https://xxx.xxxxx.cn/api"
.env.prod
VUE_APP_SERVER_API="https://xxx.xxxxx.cn/api"
.env.test
VUE_APP_SERVER_API="https://xxx.xxxxx.cn/api"
package.json文件
"scripts": {
"serve": "vue-cli-service serve --mode dev",
"build:test": "vue-cli-service build --mode test",
"build:prod": "vue-cli-service build --mode prod",
"lint": "vue-cli-service lint"
},
在页面上使用:
<script setup>
import service from "../plugins/axiosInstance"
const btn = () => {
service({
url: '/user/login',
method: 'post',
data: {
"username": "xxxxxxxxxx",
"password": "123456"
}
})
.then((res) => {
console.log('请求成功!', res)
})
}
</script>
更多推荐
已为社区贡献6条内容
所有评论(0)