我找到了使用 Rocket_cors 配置 CORS 的代码:
use rocket::http::Method;
use rocket_cors::{AllowedOrigins, CorsOptions};
let cors = CorsOptions::default()
.allowed_origins(AllowedOrigins::all())
.allowed_methods(
vec![Method::Get, Method::Post, Method::Patch]
.into_iter()
.map(From::from)
.collect(),
)
.allow_credentials(true);
rocket::build().attach(cors.to_cors())
但是当我运行程序时出现错误:
error[E0277]: the trait bound `rocket_cors::Method: From<rocket::http::Method>` is not satisfied
--> src/main.rs:37:13
|
37 | / vec![Method::Get, Method::Post, Method::Patch]
38 | | .into_iter()
39 | | .map(From::from)
40 | | .collect(),
| |__________________________^ the trait `From<rocket::http::Method>` is not implemented for `rocket_cors::Method`
|
= help: the trait `From<rocket_http::method::Method>` is implemented for `rocket_cors::Method`
我不知道如何解决这个问题。
最新发布的板条箱稳定版本(< 0.5.1) are not compatible with the latest versions of
rustc
和rocket
。
您可以使用
git
中的 branch
+ Cargo.toml
参数来使用包的开发版本。
Cargo.toml
[dependencies]
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
rocket = "0.5.0-rc.2"
此外,文档还声明使用
manage
函数而不是 attach
函数。
main.rs
#[macro_use] extern crate rocket;
use rocket::{Build, Rocket};
use rocket::http::Method;
use rocket_cors::{AllowedOrigins, CorsOptions};
#[launch]
fn rocket() -> Rocket<Build> {
let cors = CorsOptions::default()
.allowed_origins(AllowedOrigins::all())
.allowed_methods(
vec![Method::Get, Method::Post, Method::Patch]
.into_iter()
.map(From::from)
.collect(),
)
.allow_credentials(true);
rocket::build().manage(cors.to_cors())
}