微服务使用swagger-ui工具,跨域问题
问题描述使用swagger工具测试微服务时,出现端口号不一致的跨域问题,如下图解决方案在nginx中配置proxy_pass代理,解决跨域,如下配置 nginx.conf#usernobody;worker_processes1;#error_loglogs/error.log;#error_loglogs/error.lognotice;#er...
·
问题描述
使用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.html | http://localhost:3200/index.html |
http://localhost:3200/xxx | http://localhost:8080/xxx |
效果展示
写在最后
笔者也是刚接触这方面,经验不足,文章只供参考。如有不妥或误导,请不吝赐教
更多推荐
已为社区贡献1条内容
所有评论(0)