如何让服务器支持跨域
2016-12-19 · 武汉肥猫科技提供高端网站建设、SEO等服务
如果服务器是apache
(1)修改http服务的配置文件:C:\wamp\bin\apache\Apache2.4.4\conf\httpd.conf
把LoadModule headers_module modules/mod_headers.so 前面的注释删除.
(2)添加Header set Access-Control-Allow-Origin *
<Directory />
AllowOverride none
Require all granted
Header set Access-Control-Allow-Origin *
</Directory>
(3)重启http服务
如果是tomcat,比如spring MVC项目
创建一个过滤器,代码如下:
package com.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.common.dict.Constant2;
import oa.service.DictionaryParam;
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", DictionaryParam.get(Constant2.DICTIONARY_GROUP_GLOBAL_SETTING, "AccessControlAllowOrigin"));
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 {
}
}
关键代码:response.setHeader("Access-Control-Allow-Origin", "*");
修改web.xml,增加:
<filter>
<filter-name>cors</filter-name>
<filter-class>com.web.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这样服务器就支持ajax的跨域访问了