axios
Get 请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | 
 
 
 
 
 
 
 
 
 
 
 
 
 
 axios({
 url: "http://59.110.226.77:3000/api/list/hot",
 
 params: {
 cid: 16,
 },
 })
 .then((res) => {
 console.log("res", res);
 })
 .catch((error) => Promise.reject(error));
 
 | 
Post-json 请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | axios({
 url: "http://59.110.226.77:3000/api/user/login",
 method: "post",
 data: {
 
 username: this.username,
 password: this.pass,
 },
 })
 .then((res) => {
 console.log("res", res);
 })
 .catch((error) => Promise.reject(error));
 
 | 
Post-form 请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | const p = new URLSearchParams();
 p.append("username", this.username);
 p.append("password", this.pass);
 axios({
 url: "http://59.110.226.77:3000/api/user/login",
 method: "post",
 data: p,
 })
 .then((res) => {
 console.log("res", res);
 })
 .catch((error) => Promise.reject(error));
 
 | 
Post-file 请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | function upload(e) {const p = new FormData();
 p.append("file", e.target.files[0]);
 axios({
 url: "https://elm.cangdu.org/v1/addimg/shop",
 method: "post",
 data: p,
 })
 .then((res) => {
 console.log("res", res);
 this.pic = "https://elm.cangdu.org/img/" + res.data.image_path;
 })
 .catch((error) => Promise.reject(error));
 }
 
 | 
axios 自定义请求实例
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | const ins = axios.create({
 
 timeout: 20000,
 
 baseURL: "http://59.110.226.77:3000/api",
 });
 
 ins
 .get("/list/sell", {
 params: {
 cid: 17,
 },
 })
 .then((res) => {
 console.log("res", res);
 })
 .catch((error) => Promise.reject(error));
 
 | 
axios 拦截器
axios 的拦截器是用于拦截请求和响应的,也就是在数据请求前做点事,在数据请求到之后做点事
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | const ins = axios.create({
 
 timeout: 20000,
 
 baseURL: "http://59.110.226.77:3000/api",
 });
 
 
 ins.interceptors.request.use(
 (config) => {
 
 
 
 return config;
 },
 (error) => {
 
 
 return Promise.reject(error);
 }
 );
 
 
 ins.interceptors.response.use(
 (res) => {
 
 
 
 
 return res;
 },
 (error) => {
 
 
 return Promise.reject(error);
 }
 );
 
 | 
并发请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | axios.all([
 axios.get("http://59.110.226.77:3000/api/list/hot", {
 params: {
 cid: 17,
 },
 }),
 axios.get("http://59.110.226.77:3000/api/list/price", {
 params: {
 cid: 17,
 },
 }),
 ])
 .then(
 axios.spread((res1, res2) => {
 console.log("res1", res1);
 console.log("res2", res2);
 })
 );
 
 |