【问题标题】:spring read server name inside corsspring 在 cors 中读取服务器名称
【发布时间】:2020-08-05 19:51:09
【问题描述】:

我正在尝试使用端口 3000 允许来自同一服务器的 cors。

由于我不知道我的服务器将部署在哪里,所以我尝试将服务器名称作为字符串访问,而不是与我想要的端口连接。

所以这是我的方法:

@SpringBootApplication
public class TestApplication {
    @Autowired
    private HttpServletRequest request;
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println(request.getServerName());
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedOrigins(request.getServerName()+":3000");
            }
        };
    }
}

我认为这些是我的错误信息的亮点:

Error creating bean with name 'corsConfigurer'
org.springframework.beans.BeanInstantiationException: Failed to instantiate
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?

【问题讨论】:

标签: java spring spring-boot cors


【解决方案1】:

一个好的做法是在 application.properties 文件中指定允许的来源并在您的 WebConfig.class 中读取它。这样您就可以在以后轻松添加生产地址。

application.yml

web:
    allowedOrigins: 
    - "http://localhost:4200"
    - "some other"
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private final String[] allowedOrigins;

    public WebMvcConfig(@Value("${web.allowedOrigins:}") String[] allowedOrigins) {
        this.allowedOrigins = allowedOrigins;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //
            .allowedMethods("*") //
            .allowCredentials(true) //
            .allowedOrigins(allowedOrigins);
    }
}

【讨论】:

    【解决方案2】:

    只需使用localhost,无需访问服务器名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-10
      • 2013-06-16
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多