一個服務器同時接收多個域名跨域訪問 (多個域名同時跨域訪問一個服務器))

如今先後端分離開發愈來愈多了,分工愈來愈細了,前端頁面啓動的多是單獨一個域名去訪問的,而後須要調用服務器的時候涉及到跨域訪問了。好比在服務器設置http://localhost:8080的能夠訪問咱們的服務。這種單個域名跨域訪問的很簡單,可是多個域名同時跨域訪問的就要稍微處理一下才行,好比咱們的服務器能夠同時知足http://localhost:8080的和http://localhost:8081的,甚至還有http://192.168.0.2的。前端

下面是個人配置,和跨域名處理的代碼。有問題請留言。java

web.xml  添加過濾器web

<filter>
        <filter-name>cors</filter-name>
        <filter-class>com.********.server.route.filter.CrossFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

CrossFilter  代碼以下後端

 

private Logger log =   LoggerFactory.getLogger(getClass());
    
    private static List<String> configOrigin=new ArrayList<String>();
    
    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();
        log.info("初始化跨域域名");
        if(ConfigUtil.clientH5Host!=null){

           //從配置文件讀取容許跨域訪問的域名, 好比 http:localhost:8080  , 多個域名用逗號隔開就好
            configOrigin=Arrays.asList(ConfigUtil.clientH5Host.split(","));
        }
    }   

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String requestOrigin = request.getHeader("Origin");        
        log.debug("跨域設置開始,origin={}, configOrigin={}",requestOrigin, ConfigUtil.clientH5Host);
        if(requestOrigin!=null && configOrigin.contains(requestOrigin)){
            response.addHeader("Access-Control-Allow-Origin",requestOrigin);
        } else{

            //不容許訪問

        }
        response.addHeader("Access-Control-Allow-Methods", "GET, POST");
        response.addHeader("Access-Control-Allow-Headers",
                "Access-Control-Allow-Headers,Content-Type,token,token_,Access-Control-Allow-Origin,"
                + "Access-Control-Allow-Methods,Access-Control-Max-Age");
        response.addHeader("Access-Control-Max-Age", "1800");    //30 min
        response.addHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(request, response);
    }

 

關鍵配置的讀取,請看個人另外一篇文章:不一樣環境配置多個配置文件。跨域

相關文章
相關標籤/搜索