0

I'm trying to allow cors from the same server, with port 3000.

As I don't know where my server is going to be deployed, I tried to access the server name as string than concat it with my desired port.

So here is my approach :

@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");
            }
        };
    }
}

I think these are the highlights of my error message :

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?
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
  • if it's going to be depoyed on the same server, do you have any constraints on using the localhost address ? Maybe this post is helpful: https://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java – PBarri Apr 22 '20 at 17:27

2 Answers2

1

A good practice is to specify the allowed origins in the application.properties file and read it in your WebConfig.class. That allows you to easy add your production address later.

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);
    }
}

wero026
  • 1,187
  • 2
  • 11
  • 23
0

just use localhost, no need to access server name

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86