1. 安装axios
npm install axios
2. 引入axios
- 首先在src下创建utils文件夹,用来存放封装的js, 及页面接口api
在utils文件夹下创建request.js
request.js
import axios from 'axios'
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
baseURL: 'https://www.baidu.com/prod-api/',
timeout: 10000
})
service.interceptors.request.use(config => {
if (config.method === 'post') {
config.headers["Content-Type"] = "application/x-www-form-urlencoded";
}
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']';
let subPart = encodeURIComponent(params) + '=';
url += subPart + encodeURIComponent(value[key]) + '&';
}
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {
};
config.url = url;
}
return config
}, error => {
Promise.reject(error)
})
service.interceptors.response.use(res => {
return res.data
}, error => {
return Promise.reject(error)
})
export default service
3. 引入封装的axios进行api 封装
- 在utils下创建api文件引入封装好的axios
api.js
import request from '@/utils/request'
export const getPhoneCode = (query) => {
return request({
url: '/api/member/getUserPhoneCode',
method: 'get',
params: query
})
}
export const getPhoneCode = (data) => {
return request({
url: '/api/member/getUserPhoneCode',
method: 'post',
data: data
})
}
export const getPhoneCode = (id) => {
return request({
url: '/api/member/getUserPhoneCode?id='+id,
method: 'delete'
})
}
4.页面中使用
<template>
<button @click="getCode">获取验证码</button>
</template>
<script>
import {
getPhoneCode } from '../utils/api'
export default {
data(){
return {
from:{
tel:'10086'
}
}
},
methods:{
getCode(){
getPhoneCode(this.from).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
}
}
}
</script