【发布时间】:2021-09-12 11:29:43
【问题描述】:
我有一个火箭 (0.5.0-rc.1) 路线,它返回一个 content::Json<String>,我想使用 rocket_cors(来自 master)将 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 的生命周期,因为这会导致进一步的问题。
如何从我的 CORS 请求中返回 content::Json<String>?
完整的例子可以在Github找到。
【问题讨论】:
标签: rust cors rust-rocket