基于fetch cors + shiro 跨域解决方案
export function request(url, options) {
let pack={url:url,options:options};
base(pack);
return fetch(pack.url,pack.options)
.then(checkStatus)
.then(parseJSON)
.then(data => ({ data }))
.catch(err => ({ err }));
}
function base(pack){
pack.url=host+pack.url;
cookie(pack.options);
}
function cookie(options){
Object.assign(options,{credentials: 'include',mode: 'cors'});
}
后台ssm + shiro
@WebFilter("/*")
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8000");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "token,Access-Control-Allow-Origin,Access-Control-Allow- Methods,Access-Control-Max-Age,authorization");
httpServletResponse.setHeader("(Content-Type","application/json; charset=utf-8");
chain.doFilter(request, httpServletResponse);
}
遇到的问题
当headers: { ‘Content-Type’: ‘application/json’,} 后台取不到数据
- 解决方法
- 将headers 设置为headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’,}
- 将json 转为FormDATA
function JSONtoForData(data){
//let fData=new FormData();
let fData=[];
for(let key in data){
//fData.append(key,data[key]);
fData.push(`${key}=${data[key]}`);
}
return {body:fData.join("&")};
}
####问题
Fetch API cannot load http://localhost/IBaseUser/dologin. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8000' is therefore not allowed access
- Access-Control-Allow-Origin 不允许为 “*”
2.解决方法 在后台中 将 Access-Control-Allow-Origin 设置 为 前端页面的 地址 我这里是
httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8000");