I've created a simple rocket API and angular app to test things out. Rocket API works perfectly fine when called from Postman or Insomnia, but when I try to call it from angular app CORS is preventing me even though I configured CORS using rocket_cors crate. This is my rocket main function:
#[rocket::main]
async fn main() {
let cors = CorsOptions::default()
.allowed_origins(AllowedOrigins::all())
.allowed_methods(
vec![
Method::Get,
Method::Post,
Method::Delete,
Method::Put,
Method::Patch,
Method::Options,
]
.into_iter()
.map(From::from)
.collect(),
)
.allow_credentials(true)
.to_cors()
.expect("error creating CORS fairing");
let _ = rocket::build()
//.attach(cors)
.mount(
"/",
routes![get_users, get_user, create_user, update_user, delete_user],
)
.attach(cors)
.register(
"/",
catchers![not_found, unauthorized, unprocessable_entity],
)
.attach(DbConn::fairing())
.attach(AdHoc::on_ignite("Diesel migrations", run_db_migrations))
.launch()
.await;
}
and this is my Cargo.toml:
[dependencies]
rocket = { version = "0.5.0-rc.3", features = ["json"] }
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0.107"
base64 = "0.21.4"
diesel = { version = "2.0", features = ["sqlite", "r2d2"] }
rocket_sync_db_pools = { version = "0.1.0-rc", features = ["diesel_sqlite_pool"] }
diesel_migrations = "2.0"
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
I tried moving around .attach(cors) up and down, but to no avail.
This is the route:
#[get("/users")]
async fn get_users(db: DbConn) -> Result<Value, Custom<Value>> {
db.run(|c| {
UserRepository::get_all(c)
.map(|users| json!(users))
.map_err(|err|
match err {
NotFound => Custom(Status::NotFound, json!({"status": "error", "reason": "Resource was not found."})),
_ => Custom(Status::InternalServerError, json!({"status": "error", "reason": err.to_string()}))
}
)
}).await
}
This is the error message in browser:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/users. (Reason: CORS request did not succeed). Status code: (null).