Nginx跨域问题的解决方法

项目场景:

Web前端开发经常会遇到跨域访问,如果没有办法让后台开放访问域,调用接口就会被浏览器拦截。解决跨域问题的方案,可以搭建一个后台服务做中间转发,也可以用nginxicon-default.png?t=N176https://so.csdn.net/so/search?q=nginx转发。

问题描述

问题发生在nginx反向代理icon-default.png?t=N176https://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;

    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angelasp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值