来源场景:
@RequestMapping(“/captcha”)接口设置了SESSION_KEY,也能获取到,但是到了@PostMapping(“/login”)接口就是空的,由于跨域导致的两个session_id不是同一个
/*** 系统用户 前端控制器*/
@Controller
@CrossOrigin(origins = "*",maxAge = 3600)// 前端请求发生跨域错误,加入这段处理
@RequestMapping("/sys")
public class LoginController {private static final String SESSION_KEY = "captcha";@Autowiredprivate IAdminService adminService;/*** 验证码生成* @param request 请求报文* @param response 响应报文* */@RequestMapping("/captcha")public void generate(HttpServletRequest request, HttpServletResponse response) throws Exception {// 英文与数字验证码SpecCaptcha captcha = new SpecCaptcha();captcha.setLen(4);// 验证字符数// 结果String result = captcha.text();// 将结果存储到session中(由于有些验证码没存储结果,则需要自己存储,记得要转小写,可参考自带校验方法.ver)request.getSession().setAttribute(SESSION_KEY, result.toLowerCase());System.out.println("Session ID in /captcha: " + request.getSession().getId());System.out.println(request.getSession().getAttribute(SESSION_KEY));// 响应到前端captcha.out(response.getOutputStream());}/*** 登录* @return*/@PostMapping("/login")@ResponseBodypublic R login(HttpServletRequest request,@RequestBody Admin admin){
// 打印调试信息System.out.println("Session ID in /login: " + request.getSession().getId());System.out.println("SESSION_KEY retrieved in /login: " + request.getSession().getAttribute(SESSION_KEY));if(StringUtil.isEmpty(admin.getUserName())){return R.error("用户名不能为空");}if(StringUtil.isEmpty(admin.getPassword())){return R.error("密码不能为空");}String code = (String) request.getSession().getAttribute(SESSION_KEY);System.out.println(code);System.out.println(admin.getCaptcha());if (!CaptchaUtil.ver(admin.getCaptcha(), request)) {return R.error("验证码错误");}//开始数据库校验Admin resultAdmin = adminService.getOne(new QueryWrapper<Admin>().eq("userName",admin.getUserName()));if (resultAdmin==null){return R.error("用户名不存在!");}if (!resultAdmin.getPassword().trim().equals(admin.getPassword())){return R.error("用户名或密码错误!");}
// String token = JwtUtils.createJWT("-1", "admin", SystemConstant.JWT_TTL);
// Map<String,Object> resultMap=new HashMap<>();
// resultMap.put("token",token);return R.ok();}}
后端跨域配置
/*** web项目配置类*/
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS").maxAge(3600);}}
前端使用axios发请求,需要添加
withCredentials: ‘include’, // 确保请求携带Cookie
下面是封装过的axios.js文件
// 引入axios
import axios from 'axios';
let baseUrl="http://localhost:8082/"
let imageUrl = "http://localhost:1111"
// 创建axios实例
const httpService = axios.create({// url前缀-'http:xxx.xxx'// baseURL: process.env.BASE_API, // 需自定义baseURL:baseUrl,withCredentials: 'include', // 确保请求携带Cookie// 请求超时时间//timeout: 3000 // 需自定义timeout: 10000
});//添加请求和响应拦截器
// 添加请求拦截器
httpService.interceptors.request.use(function (config) {// 在发送请求之前做些什么// config.headers.token=window.sessionStorage.getItem('token') || '';return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});// 添加响应拦截器
httpService.interceptors.response.use(function (response) {// 对响应数据做点什么return response;
}, function (error) {// 对响应错误做点什么return Promise.reject(error);
});/*网络请求部分*//** get请求* url:请求地址* params:参数* */
export function get(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'get',params: params}).then(response => {resolve(response);}).catch(error => {reject(error);});});
}/** post请求* url:请求地址* params:参数* */
export function post(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'post',data: params}).then(response => {console.log(response)resolve(response);}).catch(error => {console.log(error)reject(error);});});
}/** 文件上传* url:请求地址* params:参数* */
export function fileUpload(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'post',data: params,headers: { 'Content-Type': 'multipart/form-data' }}).then(response => {resolve(response);}).catch(error => {reject(error);});});
}
export function getServerUrl(){return baseUrl;
}
export function getImageUrl(){return imageUrl;
}
export default {get,post,fileUpload
}