我有一条火箭 ( 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/