问题描述

使用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

效果展示

这里写图片描述

写在最后

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

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐