您應該添加一個篩選器,將「Access-Control-Allow-Origin」設置爲接受域「localhost:8081」(全部爲*)。
最可能的是,你會發現你的答案在這裏cores-filter-not-working
更多的解釋:
創建一個過濾器類第一
public class CorsFilter implements Filter {
private static final Logger log = Logger.getAnonymousLogger();
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
// can be moved to properties
String[] allowDomain = {"localhost:8080","localhost:8081"};
String originHeader = request.getHeader("host");
for(String domian : allowDomain){
if(originHeader.endsWith(domian))
response.setHeader("Access-Control-Allow-Origin", originHeader);
break;
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {}
}
添加映射到web.xml類
<filter>
<filter-name>cors</filter-name>
<filter-class>full name of your filter class here</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
你應該正確定義w中的URL pattren eb.xml配置根據您的requirnment
但在我的情況下,我該如何做到這一點?如果我使'response.setHeader'沒有生效,我不會返回'HttpServletResponse response'。 – PRVS
編輯我的答案,包括如何設置過濾器 – PyThon
url-pattern是哪個url? – PRVS