跨域是什么

跨域本质是浏览器基于同源策略的一种安全手段,所谓同源(即指在同一个域)具有以下三个相同点:协议相同、主机相同、端口相同。在A地址(发起请求的页面地址)向B地址(要请求的目标页面地址)发起请求时,如果A地址和B地址在: 协议 域名 端口 不全相同,则说明请求是跨域的。

解决跨域方法

1.服务器解决

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: XiongLiJian
 * @date: 2021/12/28 11:58
 * @description: 跨域处理机制
 * @version: 1.0
 */
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String origin = request.getHeader("Origin");
        String allowHeaders = request.getHeader("Access-Control-Request-Headers");
        if (!StringUtils.isEmpty(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        if (!StringUtils.isEmpty(allowHeaders)) {
            response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        } else {
            response.setHeader("Access-Control-Allow-Headers", "*");
        }
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

2.代理解决

ajax跨域去第三方接口请求数据是拿不到的,因要遵循同源策略;但是去自己的服务器要数据是不是就遵循同源策略了,再让自己的服务器去第三方的接口服务器取数据,最后再返回给ajax。使用nginx做代理服务器转发ajax请求解决跨域问题。

server
 {
     listen 80;
     listen [::]:80;
     server_name 192.168.100.151;
     index index.html;
     location / {
         root /www/wwwroot/0.control-panel;
     }
    location /api/control {
            proxy_redirect off;
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8040/api/control;
    }
 }