跨源资源共享(CORS)是指允许浏览器访问不同源的资源。只有协议(如 HTTP 和 HTTPS )、域名(如 example.com)和端口号都相同的网站才算是同源。
但在前后端分离的开发模式中,前后端应用分别运行在不同的服务器上,或者同一服务器不同端口。因此想要实现前后端CORS,就要让两者运行在同一端口,通过 Ngnix 反向代理可以实现这一需求。
假设前后端应用均部署在同一台服务器上,前端应用运行于 8080 端口,后端应用运行在 8090 端口,如果能够让两者都运行在 4000 端口,那就不存在跨域问题了,Ngnix 配置如下:
server {listen 4000;server_name localhost;location / {proxy_pass http://localhost:8080;}location /api/ {proxy_pass http://localhost:8090;}}
如此,当请求http://localhost:4000时,将转发请求http://localhost:8080;当请求http://localhost:4000/api开头的所有请求时,则请求符合http://localhost:8090/api的所有后端接口。
http://localhost:4000/api/users --> http://localhost:8090/api/users # 后端接口http://localhost:4000/api/users/1 --> http://localhost:8090/api/users/1 # 后端接口http://localhost:4000/module --> http://localhost:8080/module # 前端网页http://localhost:4000/module/api --> http://localhost:8080/module/api # 前端网页
