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

标签 rust cors rust-rocket

我有一条火箭 ( 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(基于此 example ),如下所示

#[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生命周期,因为这会导致 future 出现更多问题。

如何返回 content::Json<String>来 self 对 CORS 的请求?

完整的示例可以在 Github 上找到。 .

最佳答案

这是因为 rocket_cors生命周期限制为 Responder struct,这些使得结构体在这些生命周期边界上协变(因此它使它拒绝 'static 不应该的生命周期)。

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

我已经created a pull request ,但这将是自 Responder 以来的一个重大 API 更改在这些生命周期中将不再直接通用。如果您想继续跟踪他们的主分支,您可以按照@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))
}

更新:已合并。

关于rust - Rocket CORS如何使用Request Guard返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68192505/

相关文章:

rust - 如何在不阻塞的情况下查看 channel 并仍然能够检测到挂断?

rust - 如何摆脱 “cannot return value referencing temporary value”错误

rust - 这个 Rust 匹配表达式可以简化吗?

ajax - CORS - 对于返回 401 的 API 请求,Ajax 错误函数将错误代码报告为 0

rust - 尝试在 rust api上实现rocket_cors CorsOptions

rust - 编译器表示数据不能在线程之间安全共享,即使数据被包裹在互斥体中

rust - 在结构中引用内存的正确方法是什么

javascript - 受污染的 Canvas ,由于 CORS 和 SVG?

rust - Rocket 每晚需要最低版本的 Rust,但已经安装了更高的稳定版本

css - Gecko/Firefox 44.0.2 阻止 Google 字体