当我们使用vue请求的时候,我们会发现请求头中没有携带cookie传给后台,我们可以在请求时添加如下代码:
vue.http.options.xhr = { withCredentials: true}; 的作用就是允许跨域请求携带cookie做身份认证的;
vue.http.options.emulateJSON = true; 的作用是如果web服务器无法处理 application/json的请求,我们可以启用 emulateJSON 选项;
启用该选项后请求会以 application/x-www-form-urlencoded 作为MIME type, 和普通的html表单一样。 加上如下代码,get请求返回的代码会
携带cookie,但是post不会;
为了方便,我们这边是封装了一个get请求,只要在get请求添加参数 { credentials: true } 即可使用;
const ajaxGet = (url, fn) => { let results = null; Vue.http.get(url, { credentials: true }).then((response) => { if (response.ok) { results = response.body; fn(1, results); } else { fn(0, results); } }, (error) => { if (error) { fn(0, results); } }); };
如上只会对get请求携带cookie,但是post请求还是没有效果的,因此在post请求中,我们需要添加如下代码:
Vue.http.interceptors.push((request, next) => { request.credentials = true; next(); });
Vue.http.interceptors 是拦截器,作用是可以在请求前和发送请求后做一些处理,加上上面的代码post请求就可以解决携带cookie的问题了;
因此我们的post请求也封装了一下,在代码中会添加如上解决post请求携带cookie的问题了;如下代码:
const ajaxPost = (url, params, options, fn) => { let results = null; if (typeof options === 'function' && arguments.length <= 3) { fn = options; options = {}; } Vue.http.interceptors.push((request, next) => { request.credentials = true; next(); }); Vue.http.post(url, params, options).then((response) => { if (response.ok) { results = response.body; fn(1, results); } else { fn(0, results); } }, (error) => { if (error) { fn(0, results); } }) };
拦截器的配置
<!-- 登录拦截器 --><mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/admin/*"/> <!-- 拦截路径 -->
<mvc:exclude-mapping path="/admin/toLogin.action"/> <!-- 排除的拦截路径 -->
<bean class="com.edwin.admin.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class LoginedInterceptor implements HandlerInterceptor {
private final String ADMINSESSION = "loginedsession";
//拦截前处理
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
Object sessionObj = request.getSession().getAttribute(ADMINSESSION);
if(sessionObj!=null) {
return true;
}
response.sendRedirect("toLogin.action");
return false;
}
//拦截后处理
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception { }
//全部完成后处理
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception { }
}