I'm new to rust and I'm using rocket to create a simple CRUD API that I later would like to put on an AWS EC2 bucket. I've got one or two basic routes and I wanted to start to implement CORS so a react app can call my API. I've tried multiple tutorials and example but I'm still stuck.
Tutorials I've looked at:
- https://www.steadylearner.com/blog/read/How-to-use-CORS-and-OPTIONS-HTTP-request-with-Rust-Rocket
- https://docs.rs/rocket/0.3.6/rocket/fairing/trait.Fairing.html
[dependencies]
rocket = "0.4.6"
rocket_codegen = "0.4.6"
rocket_cors = "0.5.1"
diesel = "1.4.5"
dotenv = "0.15.0"
serde = "1.0.117"
serde_json = "1.0.59"
serde_derive = "1.0.117"
chrono = "0.4.19"
[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["json"]
My file is attached as a code snippet
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;
use std::error::Error;
use rocket::http::Method;
use rocket_cors::{AllowedHeaders, AllowedOrigins};
use rocket_contrib::json::Json;
mod notes;
mod user_creds;
use notes::Notes;
use user_creds::UserCreds;
#[get("/api/v1/db/read")]
fn read_db() -> &'static str {
"reading"
}
#[get("/api/v1/govee")]
fn govee() -> &'static str {
"Hello, govee!"
}
#[post("/api/v1/db/notes", format = "json", data = "<notes>")]
fn get_notes(notes: Json<Notes>) -> Json<Notes> {
notes
}
#[post("/api/v1/login", format = "json", data = "<user_creds>")]
fn login(user_creds: Json<UserCreds>) -> Json<UserCreds> {
println!(
"user creds, {}, {}",
user_creds.username, user_creds.password
);
user_creds
}
fn main() {
let allowed_origins = AllowedOrigins::some_exact(&["http://localhost:8080"]);
// You can also deserialize this
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors();
rocket::ignite()
.mount("/", routes![read_db])
.attach(cors)
.launch();
}
Image of error in the link:
CorsOptions::to_cors
returns aResult
, meaning that it could potentially return an error. You have to handle that error before you can use it as aFairing
:Now you can attach it as a fairing: