微服务使用swagger-ui工具,跨域问题

本文介绍如何通过配置Nginx的proxy_pass代理来解决Swagger工具在测试微服务时遇到的跨域问题。通过具体配置示例,实现了不同端口间的代理转发,并添加了必要的跨域请求头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

使用swagger工具测试微服务时,出现端口号不一致的跨域问题,如下图
这里写图片描述

解决方案

在nginx中配置proxy_pass代理,解决跨域,如下配置 nginx.conf


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    upstream proxyUrl{
        server localhost:8080;
    }
    server {
        listen       3200;
        server_name  localhost;

        #charset koi8-r;
		location  ~*\.(.*?) {  
            root   E:\文档\Projects\swagger-ui-master\dist;  
        } 
          
        #access_log  logs/host.access.log  main;
        
        location  / {
            proxy_pass http://proxyUrl;
            index  index.html index.htm;

            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                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';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
                add_header 'Access-Control-Allow-Origin' '*';
                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';
            }
            if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' '*';
                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';
            }
        }

    }
}

nginx.conf 配置项说明

	upstream proxyUrl{
        server localhost:8080;
    }
	 server {
		 listen       3200;
         server_name  localhost;
         
         location  / {
            proxy_pass http://proxyUrl;
            index  index.html index.htm;
          }
          
          location  ~* \.html$ {  
             root   E:\文档\Projects\swagger-ui-master\dist;
             index  index.html index.htm;       
         }
	 }

以上配置结果说明如下:

访问地址代理或访问地址
http://localhost:3200/index.htmlhttp://localhost:3200/index.html
http://localhost:3200/xxxhttp://localhost:8080/xxx

效果展示

这里写图片描述

写在最后

笔者也是刚接触这方面,经验不足,文章只供参考。如有不妥或误导,请不吝赐教

### 解决 Swagger 3 请求 (CORS) 问题 为了使 Swagger UI 正常工作并能够越不同源发 API 请求,在 .NET Core 或其他框架中,需确保服务器端正确配置了 CORS 支持。对于基于 ASP.NET Core 的 Web API 应用程序来说,可以通过修改 `Startup.cs` 文件来添加必要的中间件和服务。 #### 配置应用程序启动类 (`Startup.cs`) 在 `ConfigureServices(IServiceCollection services)` 方法内注册 CORS 服务: ```csharp services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://example.com") // 替换成实际前端地址 .AllowAnyHeader() .AllowAnyMethod()); }); ``` 接着,在 `Configure(IApplicationBuilder app, IWebHostEnvironment env)` 函数里调用 `UseCors()` 来应用此策略: ```csharp if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // 启用资源共享(CORS),指定使用的策略名称 "AllowSpecificOrigin" app.UseCors("AllowSpecificOrigin"); app.UseRouting(); // ...其余代码... ``` 上述操作可以有效解决 Swagger UI 发起的预检 OPTIONS 请求被拒绝的问题[^1]。 另外一种更简便的方式是在控制器级别通过 `[EnableCors]` 属性或全局范围内使用 `[assembly: EnableCors]` 注解开启 CORS 功能[^2]。不过这种方法不如前者灵活可控,建议优先考虑前者的做法。 如果项目已经集成了 Spring Cloud Gateway,则可以在网关层面上统一处理逻辑,而不需要单独为每个微服务做额外设置[^5]。 最后值得注意的是,浏览器会在真正发起 GET/POST 等正式 HTTP 请求之前先发送一个 OPTIONS 请求给目标 URL,用来询问对方是否接受来自当前页面所在网站的数据访问请求。因此除了要确保正常的业务接口能正常返回数据外,还需要特别关注这些预飞行请求能否得到恰当回应[^4]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值