Home > Web Front-end > JS Tutorial > body text

Vue2.0 axios front-end and back-end login interceptor

小云云
Release: 2018-01-02 09:29:29
Original
2016 people have browsed it

After vue was updated to 2.0, the author announced that he would no longer update vue-resource, but recommended the use of axios. Some time ago, I used vue for the first time in a project. Regarding the login problem, I will write down my experience here. This article mainly brings you a Vue2.0 axios front-end and back-end login interceptor (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

First backend:

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lovnx.gateway.po.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter{

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    User user = (User)request.getSession().getAttribute("user");
    if(user == null){
    response.sendError(401);
      return false;
    }else
      return true;
  }
}
Copy after login

The processing done here is: if there is no user in the session, a 401 error will be returned to the front end.

Front end:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import App from './App'
import router from './router'
import axios from 'axios'


// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      if (error.response.status == 401) {
          store.commit(types.LOGOUT);
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
      }
    }
    return Promise.reject(error.response.data)  // 返回接口返回的错误信息
  }
);
Copy after login

Note that the interceptor here is written in main.js.

//————————————–Separating line————————————–//

Of course, the above method The login page is written in the Vue project. Here is an example of using an independent login page combined with the Vue project.

Project directory:

The static and index.html are the things packaged by webpack.

The idea here should be combined with a previous blog post: Rewrite ajax to implement session timeout and jump to the login page

The general idea is: request any page, and the back-end interceptor intercepts it Request to check whether the user information in the session exists. If it does not exist, jump to this login.html; if it exists, respond to the data normally. Here we need to slightly change the front-end interceptor:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import App from './App'
import router from './router'
import axios from 'axios'


// http response 拦截器
axios.interceptors.response.use(
  response => {
  //这个判断是关键,如果返回登陆页面内容了,就刷新当前页面,经后端处理就会跳转到登陆页面了
  var temp = response.data + "";
      if (temp.indexOf('lkdjoifdgjdfgjdfgjfh14546') > -1) {
        router.go(0);
      }
    return response;
  },
  error => {
    if (error.response) {
      //退出登陆的时候就响应401即可
      if (error.response.status == 401) {
          router.go(0);
      }
    }
    return Promise.reject(error.response.data)  // 返回接口返回的错误信息
  }
);
Copy after login

Among them, lkdjoifdgjdfgjdfgjfh14546 is written in a hidden field of the login page.

Backend interceptor:

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lovnx.gateway.po.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter{

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestUri = request.getRequestURI();
    String contextPath = request.getContextPath();

    if (requestUri.indexOf("/login.html") > -1 || requestUri.indexOf("/system/login") > -1) {
      return true;
    }

    User user = (User)request.getSession().getAttribute("user");
    if(user == null){
      // 未登录跳转到login页面!");
        response.sendRedirect(contextPath + "/login.html");
      return false;
    }else
      return true;
  }

}
Copy after login

Related recommendations:

JAVAEE - custom interceptor, struts2 tag, login function and Verify the implementation of the login interceptor

Vue interceptor vue-resource Detailed explanation of interceptor usage

WeChat applet development page interceptor Detailed explanation

The above is the detailed content of Vue2.0 axios front-end and back-end login interceptor. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template