通过nginx解决跨域问题

nginx版本 1.29.1

问题

10.20.4.1 访问这个10.20.4.2:5000服务跨域了,麻烦处理一下

跨域报错

根据您图片中的错误信息,前端运行在 http://10.20.4.1,试图向 http://10.20.4.2:50000/upload发送 POST 请求,但被 CORS 策略阻止,因为响应中没有 Access-Control-Allow-Origin头部。

应该5000是python端口

我采用了nginx代理,添加允许跨域

bash 复制代码
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;

    sendfile on;
    keepalive_timeout 65;

    # 动态设置允许的CORS源
    # 1. 检查 map 块:确保包含 http://10.20.4.1
    map $http_origin $cors_allowed_origin {
        default "";
        "http://10.20.4.1" "http://10.20.4.1"; # 必须存在这一行
        "http://10.20.4.2" "http://10.20.4.2"; # 必须存在这一行
        # ... 其他允许的来源
    }

    server {
        listen 50000;
        server_name 10.20.4.2;

        # 2. 检查 server 或 location 块:确保添加了 CORS 头
        location / {
            # 处理 OPTIONS 预检请求
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' $cors_allowed_origin;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                add_header 'Access-Control-Allow-Headers' '*';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Length' 0;
                add_header 'Content-Type' 'text/plain; charset=utf-8';
                return 204;
            }

            # 反向代理到后端
            proxy_pass http://10.20.4.2:5000;
            # ... 其他 proxy_set_header ...

            # 为实际响应添加 CORS 头,使用 always 确保任何状态码都添加
            add_header 'Access-Control-Allow-Origin' $cors_allowed_origin always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' '*' always;
        }
    }
}

测试实际 POST 请求

此命令模拟前端实际发送的 POST 请求,检查响应是否包含 CORS 头部。

bash 复制代码
curl -X OPTIONS "http://10.20.4.2:50000" \
  -H "Origin: http://10.20.4.1" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type" \
  -v
相关推荐
原来是猿1 小时前
【Socket编程预备知识】
linux·运维·服务器·网络
吴爃1 小时前
Spring Boot 项目在 K8S 中的打包、部署与运维发布实践
运维·spring boot·kubernetes
Elastic 中国社区官方博客2 小时前
在 Elastic 中使用 MCP 自动化用户旅程以进行合成监控
大数据·运维·人工智能·elasticsearch·搜索引擎·自动化·可用性测试
长安链开源社区2 小时前
学者观察 | 基于区块链的隐私计算技术——北京理工大学教授祝烈煌
运维·区块链
learning-striving2 小时前
Ubuntu26.04下载安装教程
运维·服务器·vmware·虚拟机
码上行动 662 小时前
用U盘制作系统盘以及如何装系统
运维
invicinble2 小时前
关于搭建运维监控系统(Prometheus+Grafana)
运维·grafana·prometheus
__beginner__2 小时前
CentOS 磁盘占用异常排查与处理手册(df 高、du/ncdu 低)
linux·运维·centos
2501_927283583 小时前
荣联汇智立体仓库:为智慧工厂搭建高效“骨骼”与“中枢”
大数据·运维·人工智能·重构·自动化·制造