axios简单封装以及发送网络请求
目录结构:services->config.js,player.js,request.js
config.js:存放接口基准地址,包括对生产环境和开发环境的判断,设置延迟时间
const devBaseURL = "http://123.207.32.32:9001";
const proBaseURL = "http://123.207.32.32:9001";
export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;
export const TIMEOUT = 5000;
request.js:创建axios对象同时导入配置信息,在发送和响应阶段使用拦截器(interceptors)进行一些操作。
import axios from 'axios';
import { BASE_URL, TIMEOUT } from "./config";
const instance = axios.create({
baseURL: BASE_URL,
timeout: TIMEOUT
});
instance.interceptors.request.use(config => {
return config;
}, err => {
});
instance.interceptors.response.use(res => {
return res.data;
}, err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
console.log("请求错误");
break;
case 401:
console.log("未授权访问");
break;
default:
console.log("其他错误信息");
}
}
return err;
});
export default instance;
player.js:定义组件需要的接口并导出
import request from './request';
export function getSongDetail(ids) {
return request({
url: '/song/detail',
params: {
ids,
},
});
}
发送网络请求参数提示:
get请求参数放在params里面,作为URL请求对象
get组件内:
api.js
export function getHotRecommends(limit) {
return request({
url: '/personalized',
params: {
limit,
},
});
}
index.js
HOT_RECOMMEND_LIMIT是统一定义到公共数据的常量
const dispatch = useDispatch();
useEffect(() => {
dispatch(getHotRecommendAction(HOT_RECOMMEND_LIMIT));
}, [dispatch]);
actionCreators.js
网络请求返回的是一个dispath,在发送完网络请求并接收到返回值后调用另一个dispath将数据保存到reducer中
export const getHotRecommendAction = limit => {
return dispatch => {
getHotRecommends(limit).then(res => {
dispatch(changeHotRecommendAction(res));
});
};
};
const changeHotRecommendAction = res => ({
type: actionTypes.CHANGE_HOT_RECOMMEND,
hotRecommends: res.result,
});
reducer.js
获取到对应的action类型,通过immutable方法将数据设置到state中保存
const defaultState = Map({
hotRecommends: []
});
function reducer(state = defaultState, action) {
switch (action.type) {
case actionTypes.CHANGE_HOT_RECOMMEND:
return state.set('hotRecommends', action.hotRecommends);
}
}
——————————————取数据————————————
const { hotRecommends } = useSelector(
state => ({
hotRecommends: state.getIn(['recommend', 'hotRecommends']),
}),
shallowEqual
);
post请求参数放在data里面,作为URL请求体
post组件内(用vue代码代替):
api.js
export const login = data => {
return request({
method: 'POST',
url: 'v1_0/authorizations',
data
})
}
index.vue
import { login } from '@/api/user';
data(){
return{
user: {
mobile: '13911111111',
code: '246810',
},
}
}
const { data } = await login(this.user);
其他说明:
配置header时,如果在get、post请求中都需要,则要在common中配置,如果只是post需要则在post中配置
|