繁体   English   中英

Rocket CORS 如何使用 Request Guard 返回字符串?

[英]Rocket CORS how to return string with Request Guard?

我有一个火箭( 0.5.0-rc.1 )路线,它返回一个content::Json<String>并且我想使用rocket_cors (来自主人)将 CORS 添加到该路线。

具体来说,我想使用RequestGuard ,因为我只想为某些路由启用 CORS。

我最初的请求是这样的:

#[get("/json")]
fn json_without_cors() -> content::Json<String> {
    let test = Test {
        field1: 0,
        field2: String::from("Test"),
    };
    let json = serde_json::to_string(&test).expect("Failed to encode data.");

    content::Json(json)
}

我将其更改为使用 CORS(基于此示例),如下所示

#[get("/json")]
fn json(cors: Guard<'_>) -> Responder<'_, '_, content::Json<String>> {
    let test = Test {
        field1: 0,
        field2: String::from("Test"),
    };
    let json = serde_json::to_string(&test).expect("Failed to encode data.");

    cors.responder(content::Json(json))
}

不幸的是,这现在无法编译:

error[E0621]: explicit lifetime required in the type of `cors`
  --> src/main.rs:35:10
   |
28 | fn json(cors: Guard<'_>) -> Responder<'_, '_, content::Json<String>> {
   |               --------- help: add explicit lifetime `'static` to the type of `cors`: `Guard<'static>`
...
35 |     cors.responder(content::Json(json))
   |          ^^^^^^^^^ lifetime `'static` required

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0621, E0759.
For more information about an error, try `rustc --explain E0621`.
error: could not compile `cors_json`

我不能给Guard一个'static生命周期”,因为这会导致以后出现更多问题。

如何使用 CORS 从我的请求中返回content::Json<String>

一个完整的例子可以在Github上找到。

这是因为rocket_corsResponder结构上具有生命周期界限,并且这些使得结构在这些生命周期界限上具有协变(因此它拒绝了不应该的'static生命周期”)。

好消息是这些边界在结构体的声明中不是必需的,因为它们可以只存在于相关的impl块上。

我已经创建了一个 pull request ,但这将是一个破坏性的 API 更改,因为Responder在这些生命周期内将不再是直接通用的。 如果您想继续跟踪他们的主分支,您可以按照@Hadus 的建议进行操作,并传递一个'static作为响应者的生命周期参数。

使用 PR 的分支,您可以直接执行以下操作:

#[get("/json")]
fn json(cors: Guard<'_>) -> Responder<content::Json<String>> {
    let test = Test {
        field1: 0,
        field2: String::from("Test"),
    };
    let json = serde_json::to_string(&test).expect("Failed to encode data.");

    cors.responder(content::Json(json))
}

更新:已合并。

我能解决它的唯一方法是反复试验,但我们开始了:

fn json(cors: Guard<'_>) -> Responder<'_, 'static, content::Json<String>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM