vue发送axios请求两次完美的方法
今天在做登录注册发送验证码时,验证码一直发送两条,后来排查出原因竟然出在axios上,
一种请求方式为OPTIONS,另外一种为自己设置的。
什么是CORS通信?
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。
实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨域通信。详情见:前后分离调用API接口跨域问题
不啰嗦直接上解决方案
前台不影响,思路是直接在后台写拦截器,拦截掉没用的请求
@Configuration
public class Handler implements HandlerInterceptor {
private final static Logger logger = LoggerFactory.getLogger(d.class);
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
System.out.println("请求来了");
// 从 http 请求头中取出 token
String token = httpServletRequest.getHeader("Authorization");
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
// OPTIONS请求类型直接返回不处理
if ("OPTIONS".equals(httpServletRequest.getMethod())) {
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
@Configuration
public class SessionConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Handler()).addPathPatterns("/**");
}
}
以上就是遇到的问题,思路很简单但是卡了好长时间一直无法排查出原因出在哪里。