非jsonp解決跨域問題

一、服務器端解決跨域問題:
配置filter在filter中設置請求頭
import java.io.IOException;java

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;nginx

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;spring

@Component
public class AccessControlFilter implements Filter {
public static Logger logger = LoggerFactory.getLogger(AccessControlFilter.class);
public static final String CLIENT_CONFIG_FILE = "accessAllow.properties";

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*"); // 沒部署nginx,線上環境很差使,暫時註釋掉
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,content-type");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}跨域

}服務器

二、利用nginx反向代理解決跨域問題:
在nginx.conf配置中在http節點內添加
server {
listen 8888; #監聽端口
server_name 172.20.15.81; #監聽ip
location /maservlet/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_pass http://172.20.15.81:9080; #跳轉到路徑

}
}ide

相關文章
相關標籤/搜索