火箭中的 CORS 整流罩导致寿命错误

CORS Fairing in Rocket Causing Lifetime Errors

我正在尝试将 CORS 策略添加到我的火箭 API。我已经尝试了几种方法,但到目前为止最接近(我认为)和最直接的方法是添加自定义整流罩,在 on_response 挂钩中设置 CORS headers。我一直在使用 Fairings implementation guide and this 来解决类似的问题,但我 运行 抱怨寿命。

这是 on_response 挂钩。

fn on_response(&self, request: &Request, response: &mut Response) {
    response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
    response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, PATCH, OPTIONS"));
    response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
    response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}

运行 cargo run 产生以下错误:

error[E0195]: lifetime parameters or bounds on method `on_response` do not match the trait declaration
  --> src/main.rs:16:19
   |
16 |     fn on_response(&self, request: &Request, response: &mut Response) {
   |                   ^ lifetimes do not match method in trait

有没有办法解决终身投诉?

同样有趣的是在 Rocket 中设置 CORS 的惯用方法(我看过 rocket_cors 但是按照示例创建了一堆关于必须使用夜间构建的版本问题,但也许我错过了更直接的方法?)。

完整代码如下:

Main.rs:

use rocket::http::Header;
use rocket::{Request, Response};
use rocket::fairing::{Fairing, Info, Kind};
#[macro_use] extern crate rocket;

pub struct CORS;

impl Fairing for CORS {
    fn info(&self) -> Info {
        Info {
            name: "Add CORS headers to responses",
            kind: Kind::Response
        }
    }

    fn on_response(&self, request: &Request, response: &mut Response) {
        response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
        response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, PATCH, OPTIONS"));
        response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
        response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
    }
}

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(CORS)
        .mount("/", routes![index])
}

cargo.toml

[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rocket = "0.5.0-rc.1"
rocket_cors = "0.5.2"

在 0.5.0 中,Fairing 实现需要异步特征。

#[rocket::async_trait]
impl Fairing for CORS {
    fn info(&self) -> Info {
        Info {
            name: "Add CORS headers to responses",
            kind: Kind::Response
        }
    }

    async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
        response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
        response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, PATCH, OPTIONS"));
        response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
        response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
    }
}

(感谢@TimY 对 的评论)