SptingBoot + Vue 前后端分离开发总结
跨域问题
详情见上一篇文章 -> SpringBoot使用CROS解决跨域问题
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
每次请求session 不一致问题
后端 Controller
登录接口返回sessionId
@RestController
@RequestMapping(value = "/")
public class IndexController {
@Autowired
private HttpSession session;
@Autowired
private HttpServletRequest request;
/**
* 登录接口
* @param user
* @return
*/
@RequestMapping(value = "login")
public String login(@RequestBody User user) {
RespInfo respInfo = new RespInfo();
if (user.getUsername().equals("admin")
&&user.getPassword().equals("admin")) {
respInfo.setCode(20);
respInfo.setMsg("登录成功");
respInfo.setData(session.getId());
} else {
respInfo.setCode(50);
respInfo.setData(session.getId());
respInfo.setMsg("账号或密码错误");
}
return JSON.toJSONString(respInfo);
}
/**
* 请求接口1
* @param num
* @return
*/
@RequestMapping(value = "index1")
public String index1(String num) {
RespInfo respInfo = new RespInfo();
respInfo.setCode(20);
Map<String,String> map = new HashMap<String, String>();
map.put("num",num);
map.put("path",request.getRequestURI());
map.put("sessionid",session.getId());
respInfo.setData(map);
System.out.println(JSON.toJSONString(map));
return JSON.toJSONString(respInfo);
}
前端 vue
修改前端axios请求,在axios的全局配置
这句话的意思是每次请求都带上cookie,这样每次取请求后端,就不会被认为是不同用户导致session丢失.哦了!
axios.defaults.withCredentials = true
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import iView from 'iview';
import 'iview/dist/styles/iview.css';
Vue.config.productionTip = false
axios.defaults.withCredentials = true
Vue.use(iView)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
axios 获取error的状态值
当axios获取请求错误的时候,我们找不到error里面的具体信息
得不到里面的status和具体的信息
解决方法: 我们只需要在error后面添加error.response
然后就可以发现,具体的信息全部都出来了
参考:
https://blog.csdn.net/qq_38082304/article/details/79914994
https://github.com/niezhiliang/multy-domain-user-identifying
https://blog.csdn.net/weixin_41838204/article/details/82107567