如何解决Rocket CORS 如何使用 Request Guard 返回字符串?
我有一个火箭 (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,};
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_cors
在 Responder
结构上具有生命周期界限,并且这些使得结构在这些生命周期界限上协变(因此它拒绝 'static
生命周期,当不应该)。
好消息是这些边界在结构体的声明中不是必需的,因为它们可以单独存在于相关的 impl
块上。
我有 created a 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>>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。