需求背景
微信社交登录,获取回调信息后,希望再触发vue前端发起登录操作,故需要改变传统的vue从后台获取数据的模式,而是由后台向vue前端发起数据请求。
解决方案
JAVA后端代码
@RequestMapping("/auth/callback/{oauthType}")
public void login(@PathVariable String oauthType, AuthCallback callback, HttpServletResponse httpServletResponse) throws IOException {
String url = "http://localhost:9528/#/socialcallback?code="+oauthType+"-"+callback.getCode()+"&state="+callback.getState();
log.error("url:{}", url);
//跳转到指定页面
httpServletResponse.sendRedirect(url);
}
关键代码就是最后一行的redirect部分。
Vue前端代码
export default {
name: "SocialCallback",
created() {
const url = window.location.href.replace("#/socialcallback", "");
const code = getQueryString(url, "code");
let state = getQueryString(url, "state");
alert(code);
const type = code.split("-")[0];
// state = state.split("-")[0];
alert(state);
// 登录请求
if (type === "github") {
window.opener.location.href =
`${window.location.origin}/#/login?state=${state}&code=${code}&time=` +
new Date().getTime();
window.close();
} else {
}
},
};
此段代码接受从后台的回调,触发发起登录请求。
结后语
前后端的代码可以参考下面的开源项目