首页  >  文章  >  如何在Reactor Netty中实现CORS?

如何在Reactor Netty中实现CORS?

王林
王林转载
2024-02-05 11:57:51500浏览
问题内容

如您所知,cors 标准包括最初发送 options 请求来检查有效性,我决定在处理程序中释放对 options 请求的处理,但是出现了返回布尔值,并且仅处理 options 请求的问题,并跳过 runon 中的其余部分,也许您知道处理 cors 帮助程序请求的其他方法?

public void run() {
    HttpServer.create()
            .host(this.config.getHost())
            .port(this.config.getPort())
            .runOn(eventLoopGroup.newEventLoopGroup())
            .protocol(HttpProtocol.HTTP11)
            .handle((request, response) -> {
                if (request.method().equals(HttpMethod.OPTIONS)) 
                    return response
                        .header("Access-Control-Allow-Origin", "*")
                        .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
                        .header("Access-Control-Allow-Headers", "Content-Type, Authorization")
                        .sendHeaders();
                else 
                    ???????
            })
            .route(this.provider::run)
            .bindUntilJavaShutdown(Duration.ofSeconds(30), this::onStart);
}

正确答案


如果有人突然需要

private @notnull corsconfig getcorsconfig() {
    return corsconfigbuilder.foranyorigin()
            .allownullorigin()
            .allowcredentials()
            .allowedrequestmethods(httpmethod.get, httpmethod.post, httpmethod.delete, httpmethod.put, httpmethod.patch)
            .allowedrequestheaders("content-type", "authorization")
            .build();
}

public void run() {
    httpserver.create()
            .host(this.config.gethost())
            .port(this.config.getport())
            .protocol(httpprotocol.http11)
            .doonconnection(this::handler)
            .route(this.provider::run)
            .binduntiljavashutdown(duration.ofseconds(30), this::onstart);
}

private void addhandler() {
    this.connection.addhandlerlast(new corshandler(getcorsconfig()));
}

尝试像这样替换 handle() 来创建 http 服务器应该可以解决您的问题:

public void run() throws IOException {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().disable().build();

    HttpServer.create()
            .host(this.config.getHost())
            .port(this.config.getPort())
            .runOn(eventLoopGroup.newEventLoopGroup())
            .protocol(HttpProtocol.HTTP11)
            .handle(corsConfig)
            .route(this.provider::run)
            .bindUntilJavaShutdown(Duration.ofSeconds(30), this::onStart);
}

查看此配置的更多详细信息:https://www.php.cn/link/e2a23af417a2344fe3a23e652924091f

以上是如何在Reactor Netty中实现CORS?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除