赞
踩
Web前端开发经常会遇到跨域访问,如果没有办法让后台开放访问域,调用接口就会被浏览器拦截。解决跨域问题的方案,可以搭建一个后台服务做中间转发,也可以用nginxhttps://so.csdn.net/so/search?q=nginx转发。
问题发生在nginx反向代理https://so.csdn.net/so/search?q=%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86springboot后端应用时,前端请求后端时发生Cros错误,如下图所示。
1.Nginx作为代理服务,需要配置允许跨域
2.Springboot后台服务需要配置允许跨域请求
1.检查后台服务是否设置了允许跨域,设置方法如下:
- @Configuration
- public class WebMvcConfig implements WebMvcConfigurer {
-
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**")
- .allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
- .allowedMethods("*")
- .allowedOrigins("*")
- .allowCredentials(true);
- }
-
- /**
- * 支持PUT、DELETE请求
- */
- @Bean
- public FormContentFilter httpPutFormContentFilter() {
- return new FormContentFilter();
- }
-
- }
2.检查nginx.conf配置文件是否允许跨域,在server配置内进行配置,配置方法如下:
- location /space-time/ {
- if ($request_method = OPTIONS ) {
- add_header Access-Control-Allow-Origin "*" always;
- add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
- add_header Access-Control-Max-Age "3600";
- add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
- add_header Content-Length 0;
- add_header Content-Type text/plain;
- return 200;
- }
-
- proxy_set_header Content-Type application/json;
- add_header Access-Control-Allow-Origin "*" always;
- add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
- add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
-
- proxy_pass http://localhost:8086/space-time/;
- proxy_set_header X-Real-IP $remote_addr;
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。