layui实现请求携带token,解决跨域问题
layui实现请求携带token,解决跨域问题
Access to XMLHttpRequest at 'http://localhost:8001/admin/save' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response. 23:28:32.890 jquery.js:4 POST http://localhost:8001/admin/save net::ERR_FAILED
一,layui请求(ajax)携带token
使用localStorage保存登录成功时后端返回的token
localStorage.token = data.token;
console.log(data)
$.ajax({
type:"post",
url: requestUrl+"admin/login",
dataType:"json",
contentType:"application/json",
data: JSON.stringify(data),
success: function(data) {
console.log(data)
if(data.code == 200){
// 保存token
localStorage.token = data.token;
layer.msg(data.msg, function () {
window.location = '../index.html';
});
}else if(data.code != 200){
layer.msg(data.msg);
return false;
}
},
});
二、请求时携带token
headers: {
token : localStorage.token
}
var requestUrl = getUrl();
table.render({
elem: '#admin'
,height: 'full-50'
,url: requestUrl+'admin/page'
,toolbar: '#toolbarDemo'
,method:'post'
,contentType:"application/json"
,async: true
,headers: {
token : localStorage.token
}
,request: {
pageName: 'pageNum' //页码的参数名称,默认:page
,limitName: 'pageSize', //每页数据量的参数名,默认:limit
}
,defaultToolbar: ['filter', 'exports', 'print', {
title: '提示',
layEvent: 'LAYTABLE_TIPS',
icon: 'layui-icon-tips'
}],
cols: [[
{field:'admId', width:100, title: 'ID', sort: true}
,{field:'admUser', width:100, title: '账号'}
,{field:'admPsw', width:100, title: '密码'}
,{field:'admName', width:100, title: '用户名'}
,{field:'admSex', width:100, title: '性别', align: "center"}
,{title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
]],
limits: [5,10, 15, 20],
limit: 10,
page: true,
skin: 'line'
});
跨域问题
携带token后出现跨域
三、解决方案
在拦截器中设置允许跨域,注意在Access-Control-Allow-Headers中加入token
如下图
/**
* 拦截器,允许跨域
* @author zhang
* @date 2018年10月10日,下午2:05:39
*/
@Component
public class CrosInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");// 允许指定域访问跨域资源
//是否允许cookie
//response.setHeader("Access-Control-Allow-Credentials", "true"); //
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "18000");//Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,,在此期间不用发出另一条预检请求。
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Access-Token,token");
response.setHeader("Access-Control-Expose-Headers", "*");//响应客户端的头部 允许携带Token 等等
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
String method= request.getMethod();
String token = request.getHeader("token");
System.out.println("token:"+token);
if (method.equals("OPTIONS")){
System.out.println("跨了一下域。。。");
response.setStatus(200);
return false;
}
System.out.println("没有跨域。。。");
return true;
}
}
最后设置拦截所有请求
@Configuration
public class interceptorsConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CrosInterceptor())
.addPathPatterns("/**");//拦截请求允许跨域
//以下我自己的JWT拦截,可以不看
registry.addInterceptor(new JWTInterceptor())
.excludePathPatterns("/admin/login") //放行登录请求
.excludePathPatterns("/admin/getImage") //放行登录请求
.addPathPatterns("/admin/*"); // 拦截除了"/user/**的所有请求路径
}
}
本人也是个小白,和大家分享一下自己的一些经验,对代码的理解可能不是很透彻,这也只是给同样是小白的大家提供一下使用方法的参考而已。欢迎大佬指点错误,描述不恰当之处敬请谅解