SpringBoot 拦截器 解决Ajax跨域问题 No 'Access-Control-Allow-Origin' ........
2018-08-18
阅读 {{counts.readCount}}
评论 {{counts.commentCount}}
关于 ajax 报错
No 'Access-Control-Allow-Origin' ........
这个坑我已经踩了很多很多次了
百度清一色是jsoup解决方案,不是万全之策
我通过springboot 拦截器,给controller加http头来允许部分情况的跨域
例如我的api是在www.tczmh.club,请求的位置是bz.tczmh.club
所以理论上只要把bz.tczmh.club加入允许的范畴,就可以了
每个controller都写一遍太蠢了,发一个Springboot拦截器的实现过程
注册拦截器 默认拦截所有请求就用/**
- import com.tczmh.service.Interceptor.HeaderHandlerInterceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- @Configuration
- public class WebAppConfig implements WebMvcConfigurer {
- @Autowired
- private HeaderHandlerInterceptor headerHandlerInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // 注册拦截器
- registry.addInterceptor(headerHandlerIntercepto).addPathPatterns("/**");
- }
拦截器具体实现类
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- @Component
- public class HeaderHandlerInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
- // 这是要放行通过的域名 如果不限制用一个 * 也可以,就是不安全
- response.addHeader("Access-Control-Allow-Origin", "http://bz.tczmh.club");
- // 允许的方法 例如GET POST PUT DELETE,只要放行用过的
- response.addHeader("Access-Control-Request-Method", "POST");
- // 这个对应的是ajax里设置了header,例如存了token 或者 ontentType: "application/json"
- response.addHeader("Access-Control-Allow-Headers", "Content-Type");
- return true;
- }
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
- }
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
- }
- }
另外ajax调用如果用二级域名也有问题 会404,最好直接写全域名
- $.ajax({
- url:"http://tczmh.club/service/bz/bzContact",
- type:"post",
- .........
- });
ok。。。。
评论区空空如也,赶紧添加一条评论吧
评论 {{counts.commentCount}}
{{comment.name}}
{{comment.os}}
{{comment.browser}}
{{comment.reply.name}}
{{comment.reply.os}}
{{comment.reply.browser}}