React-Reducer中封装普通的axios请求
2019-12-01 本文已影响0人
Mr培
- 全局请求拦截 config.js
import axios from 'axios'
// 全局设定请求类型
// axios.defaults.headers.post['Content-Type'] = 'application/json'
//拦截请求
// axios.interceptors.request.use(function (config) {
// return config
// });
//拦截响应
axios.interceptors.response.use(function (config) {
console.log(config.data.code);
return config
});
- 请求封装get,post
import axios from "axios";
import qs from "qs";
import {Toast} from "antd-mobile";
const CODE ='CODE';
const LOAD_DATA ='LOAD_DATA';
const initState = {
route:'',
code:0,
data:[],
msg:''
};
export function data(state = initState,action) {
switch (action.type) {
case LOAD_DATA:
return {...state,data:action.payload,route:action.route};
case CODE:
return {...state,code:action.payload};
default:
return state
}
}
function loadData(data,route) {
return {type:LOAD_DATA,payload:data,route}
}
function toastFail(msg) {
Toast.fail(msg, 1);
return {type:CODE,payload:msg}
}
function toastInfo(msg,code) {
Toast.info(msg, 1);
return {type:CODE,payload:code}
}
export function ex_get (url, params = {}) {
return dispatch=>{
axios.get(
url,
qs.stringify(params)
).then(res => {
if (res.status === 200){
if (res.data.code === 0) {
dispatch(loadData(res.data.data))
}else{
dispatch(toastInfo(res.data.msg+'!!!',res.data.code))
}
}
}).catch(() => {
dispatch(toastFail('网络连接超时!!!'))
})}
}
export function ex_post (url, params = {},route) {
return dispatch=>{
axios.post(
url,
qs.stringify(params)
).then(res => {
if (res.status === 200){
if (res.data.code === 0) {
dispatch(loadData(res.data.data,route))
}else{
dispatch(toastInfo(res.data.msg+'!!!',res.data.code))
}
}
}).catch(() => {
dispatch(toastFail('网络连接超时!!!'))
})}
}
- 统一接口调度
import {ex_post} from '../redux/comReducer'
import {Toast} from "antd-mobile";
let myReg= /^1[3-578]\d{9}$/;
//校验手机号
export function checkPhone(phone) {
let data = {
isSend:false,
phone:phone
};
const ph = phone.replace(/\s+/g,"");
if (!ph) {
Toast.info('请填写手机号!!!', 1);
}else{
if (!myReg.test(ph)) {
Toast.info('请填写正确的手机号!!!', 1);
} else{
data.isSend = true;
data.phone = ph;
}
}
return data;
}
//发送验证码
export function sendCode(params) {
return ex_post('/api/session/send/code',params);
}
//注册
export function register(params) {
return ex_post('/api/session/register/account',params,'/rUserInfo');
}
//登录
export function login(params) {
return ex_post('/api/session/login',params,'/index');
}
//忘记密码
export function forGet(params) {
return ex_post('/api/session/reset/pwd',params,'/');
}