首页 > 解决方案 > Ajax 中的 Cors 满足 302 重定向

问题描述

我有一个端口为 8081 的前端服务器,一个端口为 8080 的后台服务器(Spring MVC + shiro)

当我向 8080 发送请求时,我必须在 8080 上设置 cors 标头

如果请求是一个简单的请求,它只返回一些 json 数据,它可以工作

但是当响应状态为 302 时,Chrome 显示

从“ http://localhost:8080/ ”重定向到“ http://localhost:8080/ ”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我认为出现这个问题有两个原因:

①如果我拦截这个302状态,处理这个response.headers.Location,我会解决这个。但我无法拦截此响应(使用 axios)

② 可能是8080服务器有些设置有问题,出现302时,服务器没有设置这个页面的cors Headers。但我不明白后端代码。

那么,①可行吗?或者我需要更改 8080 服务器上的设置?

标签: redirectcross-domainaxios

解决方案


CORS跨域会提前向OPTIONS发送请求,这个请求没有附加token,这样会导致shiro拦截请求,判断当前用户没有登录,造成问题,解决方法是继承FormAuthenticationFilter。

@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
  boolean allowed = super.isAccessAllowed(request, response, mappedValue);
  if (!allowed) {
    String method = WebUtils.toHttp(request).getMethod();
    if (StringUtils.equalsIgnoreCase("OPTIONS", method)) {
      return true;
    }
  }
  return allowed;
}

推荐阅读