Nginx前后端分离跨域的问题(springboot+html+js)

Nginx配置文件 夕阳骑士:https://www.jianshu.com/p/c872ffa500af

 listen 3333;
 server_name localhost;


location / {
       #将静态资源复制到Nginx的html下 root html; index index.html index.htm; client_max_body_size 20m; } location
/apis { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; # # Tell client that this pre-flight info is valid for 20 days # 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-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,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-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } # 匹配apis之后的路径和参数 rewrite ^.+apis/?(.*)$ /$1 break; include uwsgi_params; # 实际调用的API,springboot启动的链接 proxy_pass http://localhost:8080; }

 注意一个非常重要的问题:

此时代理已经成功,后端的原来的路径也就是http://localhost:8080依然开放,所以在静态文件,也就是ajax请求后端的路径时,应该配置为新配置的路径下,例如这个配置文件为http://localhost:3333/apis/xxxxxxx;

否则即使通过写死或者注解方式解决跨域,也会存在 session 只能存入浏览器 ,后台读取不到的情况等等。

posted @ 2021-05-20 19:51  阿蒙么么哒  阅读(276)  评论(0)    收藏  举报