1、安装
控制台输入npm install axios
或者yarn add axios
安装成功后查看package.json文件,若在dependencies中找不到axios则表明安装失败,自行百度报错
成功后截图:
2、引入——方法1
main.js中添加
import axios from 'axios'
Vue.use(axios)
完整截图如下
该方法较为麻烦
3、引入——方法2
1、导入
在src下新建目录api,api中新建index.js
如图所示
在index.js
中写入
import axios from 'axios';
let http = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: [function (data) {
let newData = '';
for (let k in data) {
if (data.hasOwnProperty(k) === true) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
}
}
return newData;
}]
});
function apiAxios(method, url, params, response) {
http({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
}).then(function (res) {
response(res);
}).catch(function (err) {
response(err);
})
}
export default {
get: function (url, params, response) {
return apiAxios('GET', url, params, response)
},
post: function (url, params, response) {
return apiAxios('POST', url, params, response)
},
put: function (url, params, response) {
return apiAxios('PUT', url, params, response)
},
delete: function (url, params, response) {
return apiAxios('DELETE', url, params, response)
}
}
配置了POST、GET、PUT、DELETE方法。并且自动将JSON格式数据转为URL拼接的方式
同时配置了跨域,不需要的话将withCredentials设置为false即可
并且设置了默认头部地址为:http://localhost:8080 ,这样调用的时候只需写访问方法即可
2、main.js中引用
import Api from './api/index.js';
Vue.prototype.$api = Api;
3、使用方法
this.$api.post('地址', {
"参数名": "参数值"
}, response => {
if (response.status >= 200 && response.status < 300) {
console.log(response.data);\\请求成功,response为成功信息参数
} else {
console.log(response.message);\\请求失败,response为失败信息
}
});
4、测试
在Home.vue中写入
运行控制台查看即可
附代码如下:
<template>
<div>
<el-button type="primary" @click="test">主要按钮</el-button>
</div>
</template>
<script>
export default {
methods:{
test(){
this.$api.get('这里填自己的接口',
{
"参数名": "参数值"
}, response => {
if (response.status >= 200 && response.status < 300) {
console.log(response.data);//请求成功,response为成功信息参数
} else {
console.log(response.message);//请求失败,response为失败信息
}
});
}
}
}
</script>
可能的错误
若出现如下报错,则表明是跨域问题,联系后端解决或自行百度跨域问题
或者可将withCredentials参数改为false再次测试即可
02/05/2022 21:40