跨域问题解决实践

​

在软件开发中,经常会遇到跨域问题,这个问题比较头疼,今天主要介绍下遇到的跨域问题解决思路及如何解决?

1、首先是后端跨域问题

spring boot中的跨域配置如下:

less 复制代码
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
//        registry.addConverter(new LongDateConverter());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

2、根据http返回状态值判断

查看nginx日志,根据返回状态排查问题。例如:上传文件调用后端接口返回413, 标识请求体过大导致跨域,nginx配置如下:

arduino 复制代码
client_max_body_size 100m;
// 默认nginx上传文件大小限制是1M

3、调用后端接口的OPTIONS(预检)请求

在某些情况下,如果你的nginx需要配置options接口,这个接口是后端没有的,是一个默认的请求,对应的nginx配置

ini 复制代码
location / {
            # if ($request_method = 'OPTIONS'){
                  add_header Access-Control-Allow-Origin *;
                  add_header Access-Control-Allow-Methods 'POST, GET, OPTIONS, DELETE';
                  add_header Access-Control-Max-Age "3600";
                  add_header Access-Control-Allow-Credentials true;
                  add_header Access-Control-Allow-Headers *;
                  add_header Content-Type 'application/json; charset=utf-8';
                  return 204;
             }
           # proxy_pass http://127.0.0.1:8115; 
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

​

相关推荐
云起SAAS1 分钟前
手机靓号选号商城H5源码 完整前后台可直接运行
前端·javascript·后端
the局外人24 分钟前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
苏三说技术24 分钟前
分库分表要被淘汰了?
后端
__underline__27 分钟前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
nice_lcj52032 分钟前
【从零理解计算机网络 · 05】TCP 四次挥手:为什么挥手要四次、TIME_WAIT 在等什么
后端·tcp/ip·计算机网络·面试·tcp·四次挥手·time_wait
Moment40 分钟前
RSI 是怎样让 AI 改进自己的 ❓❓❓
前端·后端·面试
Cosolar1 小时前
从 50ms 到 3 分钟:淘特动线 Agent 如何把 LLM 塞进一个有预算约束的实时系统
人工智能·后端·agent
Cosolar1 小时前
拆开「研发数字人」:一个 Agent 系统真正的护城河,是被结构化的判断力
人工智能·后端·架构
cong_2 小时前
🐟 我把摸鱼岛重写了!现在群聊还能装进一张表格
前端·后端·github
nice_lcj5203 小时前
【从零理解计算机网络 · 04】TCP 三次握手:为什么恰好是三次
java·后端·tcp/ip·计算机网络·面试·tcp·三次握手