跨域拦截Access-Control-Allow-Origin设置多个origin

Posted 多读书,少说话

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域拦截Access-Control-Allow-Origin设置多个origin相关的知识,希望对你有一定的参考价值。

在Extjs和java项目碰到了需要同时处理跨域,外部要访问后台接口的问题

原来的代码是这样,只能设置一个extjs前台需要过滤的跨域请求

package com.xgt.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 解决跨域问题
 */
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        
            response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:1841");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
            response.setHeader("Access-Control-Allow-Credentials", "true");
       
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

 

略微改进,给同局域网的同事访问我的接口,我设置的ip是同事的192.168.1.178,是因为他的ip访问我的接口会遭到拦截,我自己的ip不会被拦截,所以不用设置

package com.xgt.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 解决跨域问题
 */
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        String []  allowDomain= {"http://127.0.0.1:1841","http://192.168.1.178"};
        Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain));
        String originHeader=((HttpServletRequest) req).getHeader("Origin");
        if (allowedOrigins.contains(originHeader)) {
            response.setHeader("Access-Control-Allow-Origin", originHeader);
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

 

以上是关于跨域拦截Access-Control-Allow-Origin设置多个origin的主要内容,如果未能解决你的问题,请参考以下文章

PHP后端跨域HEADER头

apache跨域配置

Nginx出现双跨域问题解决

vue 使用 腾讯地图api

springboot跨域不拦截json拦截文件

javascript中跨域的http post请求