前后端交互请求基础搭建
1. 解决Cors跨域问题
推荐在后台进行解决
1.1. 方式1:配置全局设置
添加全局配置类进行开放:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Configuration public class CORSConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .allowedHeaders("*") .maxAge(3600); } }
|
1.2. 方式2:@CrossOrigin注解
在每个Controller方法上面添加允许跨域的注解:
1 2 3 4
| @CrossOrigin @RestController @RequestMapping("/student") public class StudentController {
|
2. 后端:封装Result
封装一个专门用于给前端进行封装请求用的类,比如AjaxResult
1 2 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 39 40 41 42 43 44
| package com.example.result;
public class ResultResponse {
public static Result success() { return new Result() .setResult(ResultCode.SUCCESS); }
public static Result success(Object data) { return new Result() .setResult(ResultCode.SUCCESS, data);
}
public static Result failure(ResultCode resultCode) { return new Result() .setResult(resultCode); }
public static Result failure(ResultCode resultCode, Object data) { return new Result() .setResult(resultCode, data); }
public static Result paramInvalid(Object data) { return new Result() .setResult(ResultCode.PARAMS_IS_INVALID, data); }
}
|
3. 前端:Vue安装axios
-s建议添加,如果不-s的话,虽然本地会下载axios依赖,但是并不会在package.json中添加这个依赖。当别人把代码拉下来,并不知道你用了什么依赖。(但是泽民说自己平时不-S也能使用,这就玄学了。)
4. 前端:封装request
请求与响应拦截
在src目录下,创建一个utils包,用来存放我们自己定义的工具,在utils包里创建一个request.js,来封装request请求(这东西万年不变,商业项目基本也是下面这个):
1 2 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
| import axios from 'axios'
const request = axios.create({ baseURL: 'http://localhost:8000', timeout: 5000 })
request.interceptors.request.use(config => { config.headers['Content-type'] = 'application/json;charset=utf-8';
return config }, error => { return Promise.reject(error) });
request.interceptors.response.use( response => { let res = response.data; if (typeof res === 'string') { res = res ? JSON.parse(res) : res } return res; }, error => { return Promise.reject(error) } ) export default request
|
此文件对请求和相应进行了一定的封装:
- 我们首先创建了一个axios对象,在里面设置了基本url(后端端口),设置了超时时间
- 通过axios拦截器对request请求设置了文件编码规范和token注入
- 也通过axios拦截器对response相应设置了返回值的简化
response本身上是大于后端的封装Result的,后端返回的Result是response中的data属性对应的内容。我们把response.data定义为res,以后我们直接res.code,就等同于是我们后端的Result.code。
以后我们发请求就可以直接request.就可以了,不需要直接使用axios对象。