背景 : 前后端分离项目可能会存在跨域问题, 解决跨域问题的两种方法
一 :为什么存在跨域问题
浏览器的同源策略限制默认情况下前端页面和后端服务在不同服务器(域名、端口不一样)时,前端页面js无法请求到后端接口服务,即存在跨域问题。
二 : 解决方式
1、Java代码配置跨域问题
package com.citycloud.cciop.manage.config;
import com.citycloud.ccuap.commons.application.ApplicationGlobalNames;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 跨域过滤器
*/
@Component
@Order(0)
//@WebFilter(filterName = "webFilter", urlPatterns = "/*")
public class CorsFilterS implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(CorsFilterS.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
LOG.debug("*****************aaaaaa进入全局过滤器,拦截所有请求******************");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String origin = "*";
String headers = "uias_sso_sessionid,accessToken,Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers";
if (StringUtils.isNotEmpty(ApplicationGlobalNames.RESPONSE_ALLOW_ORIGIN)) {
origin = ApplicationGlobalNames.RESPONSE_ALLOW_ORIGIN;
}
if (StringUtils.isNotEmpty(ApplicationGlobalNames.RESPONSE_ALLOW_HEADERS)) {
headers += "," + ApplicationGlobalNames.RESPONSE_ALLOW_HEADERS;
}
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", headers);
response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS,HEAD");
response.setHeader("Access-Control-Max-Age", "360");
response.setHeader("Cache-Control", "no-cache,must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
String method = request.getMethod();
if (method.equals("OPTIONS")) {
response.setStatus(200);
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
2、Linux 环境 nginx
Java只能解决后端产生请求的跨域问题,但是对于服务器上的资源是无法解决的
解决资源跨域
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
解决图片跨域
location ~* \.(apk|gif|jpg|jpeg|png|bmp|doc|docx|ppt|pptx|pdf|xls|xlsx|mp3)$ {
root /usr/local/nginx/html/;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
expires 10d;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_ignore_client_abort on;
}
3、 window 环境nginx
server {
listen 810;
server_name localhost;
location / {
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';
root ../webapp;
index index.html index.htm;
}
#error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}