【问题标题】:Global CORS configuration not working in Spring Boot全局 CORS 配置在 Spring Boot 中不起作用
【发布时间】:2019-04-17 17:20:24
【问题描述】:

所以我尝试在我的 Spring Boot 应用程序中添加一个全局 CORS 配置。当我对所有来源进行自动处理时(通过在 CorsRegistry.allowedOrigins 中添加“*”),我可以让它工作,但是当我尝试指定 http://localhost:8080 时,它不起作用。

我的控制器

@RestController
@RequestMapping("/api")
public class Controller {

    @GetMapping("/svc")
    public ResponseEntity<String> method(@RequestParam(required = false) String id) {
    //some code
    }

我的配置:

@Configuration
public class Configuration {


    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080")
                .allowedMethods("POST", "GET",  "PUT", "OPTIONS", "DELETE")
                ;
            }
        };
    }

所以这不能按预期工作。但是当我把

registry.addMapping("/**").allowedOrigins("*")

当我从客户端调用 http://localhost:8080/api/svc?id=999 时,它可以工作。

知道我在这里缺少什么吗?

谢谢!

【问题讨论】:

    标签: java spring spring-boot cors


    【解决方案1】:

    我认为你有一个复制/过去的问题,我想你的服务器在 localhost 的 8080 端口上运行。你应该知道.allowedOrigins 应该包含客户端来源,所以改变:

    registry.addMapping("/**").allowedOrigins("http://localhost:8080") 到 registry.addMapping("/**").allowedOrigins("http://localhost:[client_port]")。

    client_port 是您的客户端端口。


    编辑

    如果你想获取客户端ip,你可以将HttpServletRequest绑定到你的方法(这只是为了获取客户端地址,一旦完成你可以移除绑定):

    @GetMapping("/client/ip")
    public ResponseEntity<String> getClientIp(HttpServletRequest request) {
        String clientAddress = "";
        if (Objects.nonNull(request)) {
            clientAddress = request.getHeader("X-FORWARDED-FOR");
            if (Objects.nonNull(request) || "".equals(remoteAddr)) {
                clientAddress = request.getRemoteAddr();
            }
        }
        return ResponseEntity.ok().body(clientAddress);
    }
    

    【讨论】:

    • 哦,可能是这样。我从在 Firefox 中打开的 javascript 文件调用 API。你知道我如何检查客户端端口吗?
    • 你可以从你的浏览器中检查它(检查元素>转到网络>点击http请求然后你可以看到主机头)
    • 或者你可以将 allowedOrigins 设置为 "*" 并查看
    • 我在 Firefox 中检查了请求标头,主机是 localhost:8080。是的,使用“*”有效,但我希望能够限制允许的来源
    • @Raikyn 哦,对不起,这是我的错误,您可以查看我的编辑以了解如何获取客户地址
    猜你喜欢
    • 2019-11-13
    • 2021-04-16
    • 2019-08-25
    • 2019-01-14
    • 2019-10-25
    • 1970-01-01
    • 2019-08-25
    • 2017-10-08
    • 2018-10-15
    相关资源
    最近更新 更多