142
社区成员




这个作业属于哪个课程 | 2022年福大软件工程实践-W班 |
---|---|
这个作业要求在哪里 | 软件工程实践总结&个人技术博客 |
这个作业的目标 | 1、课程回顾与总结 2、个人技术总结 |
其他参考文献 | <<构建之法>> |
浏览器发送请求
或者接收后端数据的时候使用。更推荐使用
Axios去发送请求。轻量级请求库
,它可以拦截请求和响应
,并且相对Ajax等技术更方便上手
。get
和post
等的多种请求方法的区别
。$ npm install axios
基于bower安装$ bower install axios
使用cdn<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
四种
Axios比较常用的语法,默认的、GET和POST
,具体见以下2.2代码讲解。 axios({
method:"GET", //填写请求类型方法
url:"http://localhost:8085/xxxx" //填写请求地址
}).then(res=>{ //返回promise对象,返回数据存储在res中
console.log(res);
}).catch((err) => {
});
// 发送 POST 请求
axios({
method: 'post', //填写请求类型方法
url: '/user/12345', //填写请求地址
data: { //请求参数,采用键值对形式
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res=>{ //返回promise对象,返回数据存储在res中
console.log(res);
}).catch((err) => {
});
axios.get("http://localhost:8085/xxxx") //如果有返回参数,需要跟在url后面
.then(response=>{
console.log(response);
}).catch((err) => {
});
axios.post("http://localhost:8085/xxxx",
{title:"axios学习2", //返回参数
author:"Yehaocong2"})
.then(res=>{
console.log(res);
}).catch((err) => {
});
GET
也需要返回参数
给服务器,但是我们默认规定的GET请求方法是没有含参的,所以导致容易将POST方法和GET方法弄混,这里讲解一种可以返回参数的GET请求方法。 axios({
method: "get",
url: "http://localhost:8085/backend/teacher/showComp",
headers: { token: localStorage.token }, //请求头
params: {
competitionId: this.queryInfo.competeId, //参数名和返回内容
},
})
.then((res) => { //200-300中间都会进入
console.log(res);
if (res.data.code == "200") { //判断返回状态码,
console.log("res.data.data");
}
})
.catch((err) => { //返回错误
});
复用Axios的代码
,这里讲解怎么封装Axios方法
,方便使用。//request.js
import axios from "axios";
import qs from "qs";
import app from "../main.js";
2、创建Axios实例const service = axios.create({
baseURL: process.env.BASE_URL, // api的base_url
timeout: 6000 // 请求超时时间
});
3、使用拦截器,进行统一配置service.interceptors.request.use(config => {
config.method === 'post' //设置方法
? config.data = qs.stringify({...config.data}) //设置请求参数
: config.params = {...config.params};
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return config;
}, error => { //请求错误处理
//错误请求处理内容
Promise.reject(error)});
4、对响应进行统一处理service.interceptors.response.use(
response => { //成功请求到数据
//这里根据后端提供的数据进行对应的处理
if (response.data.data === '200') { //根据返回状态码进行处理
return response.data;
} else {
}
},
error => { //响应错误处理
console.log(error); //错误响应内容放在error中
let text = JSON.parse(JSON.stringify(error)).response.status === 404
? '404'
: '网络异常,请重试';
return Promise.reject(error)
}
);
5、暴露Axios实例export default service; //service是实例名字
6、调用Axios接口data
中,get请求参数放在params
中。import service from './request' //引入Axios实例
export const getCompetitionInfo = data => { //返回响应结果
return service({
url: '/backend/showCompitition', //省去了ip地址,只需要填写路径即可
method: 'post',
data{
competitionID:this.ID,
userID: this.userId
}
})
};
4.1、Axios特点
promise
的异步ajax请求库
拦截器
数据转换
4.2 使用Axios需要注意的细节
不要弄混
get和post还有这两种默认方式的方法的使用,尤其是当get含参
的时候,容易错用post的方法去发起get请求。封装Axios
,暴露出Axios的实例
,进行调用
,防止需要更改url地址的时候产生混淆。