Axios

发布时间 2023-05-29 15:02:39作者: 谭五月

Axios 请求方式与后端接口的对应关系

一、GetMapping

@GetMapping("/getCompanyData")
@ResponseBody
public void getCompanyData(@RequestParam String systemType){
    System.out.println("get:  " + systemType);
}

前端只可以使用key-value对象的方式,且参数对象的key名称必须为params

axios.get('http://localhost:8080/getCompanyData', 
    {
    params: {
        systemType: 'get'
    }
}).then((res) => {
    console.log(res);
}).catch(function (error) {
    console.error(error);
});

二、PostMapping

2.1、后端使用 @RequestParam 接收具体的参数
@PostMapping("/getCompanyData")
@ResponseBody
public void getCompanyDataPost(@RequestParam String systemType){
    System.out.println("post:  " + systemType);
}

前端应使用FormData来组织请求参数,可以用于普通参数,也可以用于上传文件

var formData = new FormData();
formData.append('systemType', 'post');

axios.post('http://localhost:8080/getCompanyData', formData)
    .then((res) => {
    	console.log(res);
    }).catch(function (error) {
        console.error(error);
    });
2.2、后端使用 @RequestBody 接收对象
@PostMapping("/getCompanyData")
@ResponseBody
public void getCompanyDataPost(@RequestBody Object object){
    System.out.println(object);
}

前端应使用key-value对象来组织参数,且content-Type: 'application/json'

axios.post('http://localhost:8080/getCompanyData', 
	{
		systemType: 'post'
	}).then((res) => {
    	console.log(res);
    }).catch(function (error) {
    	console.error(error);
    });

三、 拦截器

3.1、请求拦截器

axios.defaults.withCredentials = true;

axios.interceptors.request.use(
    config => {
        config.url = baseUrl + config.url;
        return config
    },
    error => {
        return Promise.reject(error);
    }
)

3.2、响应拦截器

axios.interceptors.response.use(
    response => {
        if(response.data.code === 200){
            return response.data;
        }

        //请求时发送了clientToken,但是数据库没有该token,说明该计算机权限已被删除
        if(response.data.code === 401){
            common.openMessage('error', '您的授权已被收回,请重新认证!');
            indexApp.setCookie('clientToken', '', -1);
            localStorage.removeItem('clientToken');
            indexApp.auth = false;
            return;
        }
        common.openMessage('error', response.data.message);
        return null;
    },
    error => {
        switch (error.response.status){
            case 401:
                console.log(error);
                common.openMessage('error', '您无权进行该操作');
                break
            default: common.openMessage('error', error.response.statusText);
        }
        return Promise.reject(error);
    }
);