lawliet89 / rocket_cors

Cross-origin resource sharing (CORS) for Rocket.rs applications

Home Page:https://lawliet89.github.io/rocket_cors/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cors Partially working

Tevinthuku opened this issue · comments

commented

I'm facing a weird scenario with cors, so I built an electron app and when it interacts with my API I get a response back. The electron app uses Axios to handle data fetching and it works

image

But when I call the same request in my web application built with (Next Js), I get a 403 error on the options request.

image

Below is a snippet of what my server looks like. It's fairly simple.


#![feature(proc_macro_hygiene, decl_macro)]

use js_typify_gostruct;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
use rocket::http::Method;

use rocket::response::status::BadRequest;
use rocket_contrib::json::{Json, JsonValue};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Error};

use rocket::Request;

#[derive(Serialize, Deserialize)]
struct TransformRequest {
    contents: String,
}

#[post("/gostruct/to/flow", format = "json", data = "<data>")]
fn transform_go_struct_to_flow(
    data: Json<TransformRequest>,
) -> Result<JsonValue, BadRequest<JsonValue>> {
    match js_typify_gostruct::transform(data.contents.to_string()) {
        Ok(res) => Ok(json!({ "data": res })),
        Err(parse_error) => Err(BadRequest(Some(json!({
            "status": "error",
            "reason": format!("{:?}", parse_error)
        })))),
    }
}

#[catch(404)]
fn not_found(req: &Request) -> JsonValue {
    json!({
        "status": "error",
        "reason": format!("Sorry, '{}' is not a valid path.", req.uri())
    })
}

fn main() -> Result<(), Error> {
    let allowed_origins = AllowedOrigins::All;
    let cors = rocket_cors::CorsOptions {
        allowed_origins,
        allowed_methods: vec![Method::Get, Method::Post, Method::Options]
            .into_iter()
            .map(From::from)
            .collect(),
        allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
        allow_credentials: true,
        ..Default::default()
    }
    .to_cors()?;
    rocket::ignite()
        .mount("/api/v1", routes![index, transform_go_struct_to_flow])
        .register(catchers![not_found])
        .manage(cors)
        .launch();

    Ok(())
}

Am I missing something here

This is a little strange. In your Rocket.toml, can you set log = "debug" and see if Rocket gives you the reason why it's 403?

commented

I switched from using the fetch API to using Axios so now It says the options route isn't found, so here's the output (404)

OPTIONS /api/v1/gostruct/to/flow:
    => Error: No matching routes for OPTIONS /api/v1/gostruct/to/flow.

image

You used Rocket::ignite().manage(cors). This is the request guard method that requires more work to use CORS.

If you want to use fairing, you should use the Rocket::ignite().attach(cors) method. See example.

commented

I missed that. Thank you for your help 👍 . I'll close this issue since I have no further questions