封装axios

封装axios

 

npm i axios

 

页面导入axios

import axios from "axios"

 

const http = axios.create({
baseURL: '',

//超过事件未响应
timeout: 3000,
headers: { 'Content-type': 'application/json' }
});

 

// 添加请求拦截器

http.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
Toast.show({
icon: 'loading',
content: '加载中…',
duration: 0
})
// let token = localStorage.getItem('token');
// config.headers.token = token;
return config;
}, function (error) {
// 对请求错误做些什么
Toast.clear();
return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
Toast.clear();
// let token = response.headers.token;
// localStorage.setItem("token", token)
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
Toast.clear();
return Promise.reject(error);
});
//封装 axios 的get post请求
const ajax = {
get(url: string, data: any, headers: any = {}) {
return http.get(url, {
headers: {
...headers
},
params: {
...data
}
})
},
post(url: string, data: any, headers: any = {}) {
return http.post(url, {
headers: {
...headers
},
data: {
...data
}
})
}
}

export default ajax;

 

引入上面封装好的axios请求

import http from "./utils/http";

 

请求数据:

import React, { useEffect } from 'react'

 

在react 的useEffect的回调函数里面 请求数据

useEffect(() => {
http.get("/gateway", {
cityId: 210300,
pageNum: 1,
pageSize: 10,
type: 1,
k: 267213
}, {
"X-Client-Info": '{"a":"3000","ch":"1002","v":"5.2.1","e":"16753253105169126284722177","bc":"210300"}',
"X-Host": "mall.film-ticket.film.list"
}).then(res => {
console.log(res.toString());
})
}, [])

 

梓旭梓旭
THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录