zoukankan      html  css  js  c++  java
  • JS跨域访问CORS配置

    两个方法

    一、配置Filter,每个请求都拦截,设置Http Header

    Web.xml

    <filter>
        <filter-name>cros</filter-name>
        <filter-class>cn.ifengkou.test.filter.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cros</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    Java

    public class CORSFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
            filterChain.doFilter(request, response);
        }
    }

    二、使用Spring4.2版本以上,使用CrossOrigin注解

    @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
        @RequestMapping("/{id}")
        public Account retrieve(@PathVariable Long id) {
            // ...
        }
    
        @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
        public void remove(@PathVariable Long id) {
            // ...
        }
    }
    

      

  • 相关阅读:
    c/c++字符串传递
    从一个小程序明白new和delete的奇特现象
    Linux下构造函数string需要注意的问题
    字符串转time_t
    CentOS7基础建站指南(笔记)
    图与搜索
    面向的对象编程的小猫腻
    多线程编程
    生产者消费者模式-Java实现
    Java-代理模式的理解
  • 原文地址:https://www.cnblogs.com/kevin19900306/p/6065576.html
Copyright © 2011-2022 走看看