跨域

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011897110/article/details/86303478

一、什么是跨域
简单来说:协议,域名,端口只要有一个不同就算跨域。因为浏览器同源策略的限制,不允许页面跨域调用其他页面的对象
(浏览器同源策略:域名相同;协议相同;端口相同)
二、解决方案

  1. 服务器端将访问返回的数据的消息头进行修改。在服务器端,返回数据到客户端主要是依靠response进行的操作。加入下面的代码即可实现跨域的数据传输:
    respons.setHead(“Access-Control-Allow-Origin”,"");
    其中
    代表任意连接,这里可以替换为前端页面服务器的ip
  2. 过滤器filter
	public class SimpleCORSFilter implements Filter{  
	    @Override  
	    public void destroy() {  
	    }  
	    @Override  
	    public void doFilter(ServletRequest req, ServletResponse res,  
	            FilterChain chain) throws IOException, ServletException {  
	            HttpServletResponse response = (HttpServletResponse) res;  
	            response.setHeader("Access-Control-Allow-Origin", "*");  
	            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
	            response.setHeader("Access-Control-Max-Age", "3600");  
	            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");  
	            chain.doFilter(req, res);  
	    }  
	    @Override  
	    public void init(FilterConfig arg0) throws ServletException {  
	    }  
	}
  1. 拦截器interceptor
	@Component
	public class CORSInterceptor extends HandlerInterceptorAdapter {
	  @Override
	  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	      //添加跨域CORS
	      response.setHeader("Access-Control-Allow-Origin", "*");
	      response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
	      response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
	      return true;
	  }
	}
  1. springboot配置Cors跨域

全局配置

	@Configuration
	public class WebAppConfigurer extends WebMvcConfigurerAdapter {
	    @Override
	    public void addCorsMappings(CorsRegistry registry) {
	        registry.addMapping("/**")
			        //.allowedOrigins("http://192.168.89.89")
	                .allowedMethods("GET", "POST","DELETE")
	                .allowCredentials(false).maxAge(3600);
	    }
	}

单个接口配置

	@CrossOrigin(origins = "*", maxAge = 3600) //* 可以改成ip地址
    @PostMapping("save")
    public ResponseEntity<Result> addNote(@RequestParam String noteName){}
展开阅读全文

没有更多推荐了,返回首页