首页 > 解决方案 > 带有查询参数的路径上顶点中的 Cors

问题描述

我有域A 和域B。

domainA 向 domainB 发送 API。我想为 Vertx 添加Cors功能,以确保发送 API 的是我的 domainA。其余的是具有查询参数的 URL。

例如到这个 URL:/hello?queryParam=var。

我想做这样的事情:

router.route(".../hello?queryParam=var").handler(CorsHandler.create("specificOriginDomain")

但我也有另一个 API(在代码中的不同位置)具有相同的 URL,但没有查询参数:“.../hello”,我不想用 Cors 阻止

如何阻止(使用 Cors)与他的查询参数相关的特定 URL?

标签: corsvert.xquery-parameters

解决方案


如果我正确理解目标是CORS只有在有 HTTP 参数的情况下。在这种情况下,您需要编写一个自定义处理程序。这是一个简单的例子:

// create the desired CORS handler to check CORS as you desire
// this handler is not be used directly but will be used 
CORSHandler cors = CORSHandler.create(...);

Handler<RoutingContext> myCORSHandler = (ctx) -> {
  if (ctx.request().getParam("var") != null) {
    // your request contains the parameter "var" so
    // we will make it go through the CORS Handler
    cors.handle(ctx);
  } else {
    // the request is "safe" so we ignore the CORS
    // and go to the next handler directly
    ctx.next();
  }
});

// later in your application, just use your CORS handler
Router app = Router.router(vertx);
...
app.route().handler(myCorsHandler);
app.route().handler(ctx -> {
  // depending in the params when you reach here, the CORS
  // have been checked or not...
  // if you want to know which case happened, just add a
  // property to the context in the "if" statement in the
  // custom handler, e.g.: ctx.put("CORS", true)
});

推荐阅读