Java - Spring Boot:Access-Control-Allow-Origin 不起作用 [英] Java - Spring Boot: Access-Control- Allow-Origin not working

查看:35
本文介绍了Java - Spring Boot:Access-Control-Allow-Origin 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用一些教程和

解决方案

最后,我通过在我的 Application 类中添加以下内容解决了这个问题.

@Bean公共 WebMvcConfigurer corsConfigurer() {返回新的 WebMvcConfigurer() {@覆盖公共无效 addCorsMappings(CorsRegistry 注册表){registry.addMapping("/**").allowedOrigins(https://example.com",https://www.example.com",http://192.168.1.12:3000",http://localhost:3000");}};}

因此最终的 Application 类将类似于此

@SpringBootApplication@EnableScheduling@EnableAsync公共类 ExampleApplication {公共静态无效主(字符串 [] args){SpringApplication.run(ExampleApplication.class, args);}@豆公共 WebMvcConfigurer corsConfigurer() {返回新的 WebMvcConfigurer() {@覆盖公共无效 addCorsMappings(CorsRegistry 注册表){registry.addMapping("/**").allowedOrigins(https://example.com",https://www.example.com",http://192.168.1.12:3000",http://localhost:3000");}};}}

I tried to implement Access-Control- Allow-Origin in spring boot using few tutorials and this link but not able to implement this.

To implement this, in application.properties file, I added below line

endpoints.cors.allowed-origins=https://example.com

Which probably means that except the URL https://example.com, no other endpoint can call any APIs. But it's not working I still can see * in response , in below image. Which menas from other domains, my APIs are accessible. So how to prevent this?

解决方案

Finally, I resolved this problem by adding the following in my Application class.

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
}

So the final Application class will look something similar to this

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(ExampleApplication.class, args);
}

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("https://example.com",
                            "https://www.example.com",
                            "http://192.168.1.12:3000",
                            "http://localhost:3000");
        }
    };
   }
}

这篇关于Java - Spring Boot:Access-Control-Allow-Origin 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆