當使用者直接輸入位址的時候,會被伺服器要求重定向到http://localhost:8081/login要求使用者登入才可以通路,當後端将http://localhost:8081/login傳回給前端,前端會直接通路這個位址,就不經過node.js代理。沒有代理就跨域了。
解決方案1:在login的接口上使用@CrossOrigin注釋
解決方案2:
protected void configure(HttpSecurity http) throws Exception
以上方法中加入以下代碼:
.csrf().disable()
// 沒有認證時,在這裡處理結果,不要重定向
.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
RespBean error = RespBean.error("通路失敗");
if (e instanceof InsufficientAuthenticationException){
error.setMsg("尚未登入,請登入(請求失敗)");
}
out.write(new ObjectMapper().writeValueAsString(error));
out.flush();
out.close();
}
2.當使用者直接輸入位址後,不能還停留在空白頁,要傳回到home頁
在前置導航守衛中
如下判斷
如果使用者去的是home直接去
否則判斷是由存在使用者資訊,有正确跳轉,沒有跳轉home頁
if (to.path == '/'){
next();
}else{
if (window.sessionStorage.getItem("user")) {
initMenu(router,store);
next();
}else{
next('/')
}
}
3.實作當使用者直接輸入位址後,跳轉home頁,當使用者登入後直接跳轉到使用者輸入的位址位置
否則判斷是由存有使用者資訊,有正常跳轉,沒有拼接重定向
if (to.path == '/'){
next();
}else{
if (window.sessionStorage.getItem("user")) {
initMenu(router,store);
next();
}else{
next('/?redirect='+to.path)
}
}
下面是登入頁面的登入方法
submitLogin(){
this.$refs.loginForm.validate((valid) => {
if (valid) {
postKeyValueRequest('/doLogin',this.loginForm).then(resp=>{
if (resp) {
window.sessionStorage.setItem("user",JSON.stringify(resp.obj))
// 擷取redirect重定向的位址
let path = this.$route.query.redirect;
// path是home頁或者沒定義直接跳home頁 否則跳重定向的位址
this.$router.replace((path == '/'||path == undefined)?'/home':path)
}
})
} else {
console.log('error submit!!');
return false;
}
});
}