一、介绍
Axios 是一个基于promise的网络请求库。(读音:艾克丝伊欧姿)
中文文档:https://www.kancloud.cn/yunye/axios/234845/
二、特点
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
三、使用
1、安装
npm install --save axios
2、引入
2-1、局部引入
在需要用到axios请求的组件文件中,引入:import axios from “axios”。在组件中,直接 axios({}) 使用。
2-2、全局引入
修改项目中的main.js文件,改动如下:
import axios from "axios"
const app = createApp(App);
app.config.globalProperties.$axios = axios;
app.mount("#app")
在其他组件中,不需要再重复引入axios,直接 this.$axios({}) 使用即可。
3、使用
我通过SpringBoot写了个web demo用于接收网络请求。
jar 包地址:https://cdn.yiduoyun.space/vue_axios_web_jar/api_demo-0.0.1-SNAPSHOT.jar
接口文档:https://console-docs.apipost.cn/preview/ff77c49e9e00e577/c365ef9996ed38fb
下面我将围绕这个demo进行axios的get、post、put、delete请求演示。
前端跨域处理
由于浏览器同源策略问题,即前端和后端必须是同种协议、同个域名、同个端口的情况下才能正常访问。面对这个问题,在vue中的处理方式为:
编辑 vue.config.js 文件,添加 devServer 参数说明允许跨域。
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
//所有请求都匹配
'/': {
//服务端域名
target: 'http://localhost:80',
//允许跨域
changeOrigin: true
//避免项目中存在websocket配置的代理;初始建立连接没有问题,能连接成功 ;但是一会就报错(Invalid frame header)
ws: false
}
}
}
})
Get 请求
<template>
<div>
<p>id:{{ id }}</p>
<p>msg:{{ msg }}</p>
data:
<p v-for="item in data" :key="id">
{{ item }}
</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
data(){
return{
id: 0,
msg: "",
data: []
}
},
mounted(){
axios({
method: "get",
url: "/getInfo"
}).then(res =>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
}
</script>
<style scoped></style>
简写:
mounted(){
axios.get("/getInfo").then(res =>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
Post 请求
post 请求from表单,需要依赖一个类型转换组件 querystring。
npm install --save querystring
import qs from 'querystring';
mounted(){
axios({
method: "post",
url: "/addInfo",
data: qs.stringify({
name: "陈七"
})
}).then(res =>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
简写:
import qs from 'querystring';
mounted(){
axios.post("/addInfo",qs.stringify({
name: "陈七"
})).then(res => {
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
Put 请求
import qs from 'querystring';
mounted(){
axios({
method: "put",
url: "updateLastInfo",
data: qs.stringify({
name:"熊大"
})
}).then(res => {
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
简写:
import qs from 'querystring';
mounted(){
axios.put("/updateLastInfo",qs.stringify({
name: "熊二"
})).then(res =>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
Delete 请求
mounted(){
axios({
method: "delete",
url: "removeLastInfo"
}).then(res => {
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
简写:
mounted(){
axios.delete("removeLastInfo").then(res => {
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
4、网络请求封装
在日常应用过程中,一个项目的网络请求会很多,此时一般采用的方案是将网络请求封装起来,方便后续使用。
在src目录下创建文件夹 utils ,并创建文件 request.js,用来存储网络请求对象 axios
import axios from "axios";
import querystring from "querystring"
const errorHandle = (status,info) => {
switch(status){
case 400:
console.log("语义有误");
break;
case 401:
console.log("服务器认证失败");
break;
case 403:
console.log("服务器拒绝访问");
break;
case 404:
console.log("地址错误");
break;
case 500:
console.log("服务器内部错误");
break;
case 502:
console.log("服务器无响应");
break;
default:
console.log(info);
break;
}
}
const instance = axios.create({
//网络请求的公共配置
timeout: 5000,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
}
})
//拦截器
//发送数据之前
instance.interceptors.request.use(
config =>{
// config:包含网络请求的所有信息
if(config.method === "post" || config.method === "put"){
config.data = querystring.stringify(config.data)
}
return config;
},
error =>{
return Promise.reject(error)
}
)
//转发响应之前
instance.interceptors.response.use(
response => {
return response.status === 200 ? Promise.resolve(response) : Promise.reject(response)
},
error =>{
const { response } = error;
errorHandle(response.status,response.info)
}
)
export default instance;
在文件夹 api 下创建文件 path.js,用来记录接口地址
const base = {
//baseUrl,当域名存在跨域,由前端处理时,不能使用该baseUrl指定域名,使用了就会跨域。
baseUrl: "http://localhost",
getInfo: "/getInfo",
addInfo: "/addInfo",
updateLastInfo: "/updateLastInfo",
removeLastInfo: "/removeLastInfo"
}
export default base;
在src目录下创建文件夹 api ,并创建文件 index.js,用来封装、定义接口
import axios from '../utils/request'
import path from './path'
const api = {
//获取信息api
getInfo(){
// return axios.get(path.baseUrl + path.getInfo)
return axios.get(path.getInfo);
},
//添加信息api(带参数)
aaddInfo(name){
return axios.post(path.addInfo,{
name: name
});
}
}
export default api
封装后的api使用方法
import api from '../api/index'
export default {
name: 'HelloWorld',
data(){
return{
id: 0,
msg: "",
data: []
}
},
mounted(){
/* api.getInfo().then(res=>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
}) */
api.aaddInfo("陈七").then(res=>{
console.log(res.data);
this.id=res.data.id;
this.msg=res.data.msg;
this.data=res.data.data;
})
}
}
评论区