Skip to content

Commit 9b4a588

Browse files
committed
fix: CORS *should* be working now
1 parent ed36824 commit 9b4a588

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

src/main.rs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ use dotenv::dotenv;
99
#[macro_use]
1010
extern crate rocket;
1111
use rocket::{
12-
http::{Method, Status},
13-
Request,
12+
fairing::{Fairing, Info, Kind},
13+
http::{Header, Status},
14+
Request, Response,
1415
};
15-
use rocket_cors::{AllowedOrigins, CorsOptions};
1616

1717
use crate::controllers::contactinfo_controller::get_contactinfo;
1818
use crate::controllers::location_controller::get_locations;
@@ -27,7 +27,7 @@ fn default_catcher(status: Status, _: &Request) -> Option<CustomError> {
2727
}
2828

2929
#[launch]
30-
fn rocket() -> _ {
30+
async fn rocket() -> _ {
3131
dotenv().ok();
3232
let uri = match env::var("DATABASE_URL") {
3333
Ok(v) => v.to_string(),
@@ -44,15 +44,32 @@ fn rocket() -> _ {
4444
Err(_) => panic!("Couldn't connect to database"),
4545
};
4646

47-
let cors = CorsOptions::default()
48-
.allowed_origins(AllowedOrigins::all())
49-
.allowed_methods(vec![Method::Get].into_iter().map(From::from).collect())
50-
.allow_credentials(true);
47+
pub struct CORS();
48+
49+
#[rocket::async_trait]
50+
impl Fairing for CORS {
51+
fn info(&self) -> Info {
52+
Info {
53+
name: "Add CORS headers to requests",
54+
kind: Kind::Response,
55+
}
56+
}
57+
58+
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
59+
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
60+
response.set_header(Header::new(
61+
"Access-Control-Allow-Methods",
62+
"POST, GET, PATCH, OPTIONS",
63+
));
64+
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
65+
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
66+
}
67+
}
5168

5269
rocket::build()
53-
.attach(cors.to_cors().unwrap())
5470
.register("/", catchers![default_catcher])
5571
.manage(db)
72+
.attach(CORS())
5673
.mount(
5774
"/",
5875
routes![

0 commit comments

Comments
 (0)