在vue根目录先执行下载axios
npm install axios --save
在src 目录下创建 utils/request.js
import axios from "axios";
const instance = axios.create({
baseURL: "http://****:8080",
timeout: 5000,
headers: {},
});
instance.interceptors.request.use(
function (config){
if (token是否存在){
config.headers.authorization=`token号`;
}
return config;
},
function (error) {
return Promise.reject(error);
}
)
instance.interceptors.response.use(
function (response){
return response.data;
},
function (error){
return Promise.reject(error);
}
)
export const get = (url, params) => instance.get(url, { params });
export const post = (url, data) => instance.post(url, data);
export const del = (url, params) => instance.delete(url, { params });
export const put = (url, data) => instance.put(url, data);
在src下创建 api目录。此目录下放接口api
例: src下创建 api/user.js
import {get,post} from "../utils/request";
export const login = (data)=>get('/api/login',data);
export const getUserInfo = (data)=>post('/api/getuser',data)
export const delUser = (data)=>del('/api/delUser',data)
export const upUser = (data)=>put('/api/upuser',data);
在模块中使用: pages/user.vue
<template>
<div id="user">
</div>
</template>
<script>
import { login, getUserInfo, delUser , upUser } from "@/api/user";
export default {
data(){
return {
token:'',
userInfo:'',
}
},
created(){
this.getuser();
this.login();
},
methods:{
async login(){
let result = await login({phone:'188888888',password:'111111'});
if(result.status === 200){
this.token = result.token;
}
},
getInfo(){
getUserInfo({'token':''}).then(res=>{
console.log(res)
})
},
},
}
</script>
<style scoped>
</style>
|