跨域
由于浏览器的同源策略,当请求的URL(协议,域名,端口)和当前页面的URL不同,就会出现跨越问题
方案一:SpringBoot配置
如果用了SpringBoot,那么配置一个跨域配置即可
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .maxAge(3600) .allowCredentials(true); } }
方案二:用Nginx反向代理解决
nginx.conf
server { # 站点监听端口 listen 9000; # 站点访问域名 server_name 127.0.0.1; # 编码格式 charset utf-8; # 本地访问 http://127.0.0.1:9000/,真实访问的是后端服务地址 location / { # 后端服务地址 proxy_pass http://172.27.24.63:8001/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 100; proxy_send_timeout 300; proxy_read_timeout 600; client_max_body_size 200m; } # 本地访问 http://127.0.0.1:9000/service1/ location /service1/ { # 后端服务地址 proxy_pass http://172.27.24.63:8002/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_request_headers on; proxy_hide_header Cache-Control; } # 本地访问 http://127.0.0.1:9000/service2/ location /service2/ { # 后端服务地址 proxy_pass http://172.27.24.63:8003/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_request_headers on; proxy_hide_header Cache-Control; } }
配置了反向代理,启动Nginx后,你前端只需要访问location的地址即可。精简版的你可以只留proxy_pass
server { # 站点监听端口 listen 9000; # 站点访问域名 server_name 127.0.0.1; # 编码格式 charset utf-8; # 本地访问 https://127.0.0.1:9000/,真实访问的是后端服务地址 location / { # 后端服务地址 proxy_pass http://172.27.24.63:8001/; } # 本地访问 https://127.0.0.1:9000/service1/ location /service1/ { # 后端服务地址 proxy_pass http://172.27.24.63:8002/; } # 本地访问 https://127.0.0.1:9000/service2/ location /service2/ { # 后端服务地址 proxy_pass http://172.27.24.63:8003/; } }