How to set up CORS or OPTIONS for Rocket.rs

前端 未结 2 1647
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 18:35

I\'ve got a backend running rocket.rs which my flutter web app sends a request to, but it can\'t get past the OPTIONS response.

I have tried adding CORS (rocket_cors) t

2条回答
  •  长情又很酷
    2021-01-22 19:20

    In order for a server to provide an external API it needs to be able to deal with Cross Origin Resource Sharing (CORS). CORS is an HTTP-header based mechanism that allows a server to indicate which origins (domain, protocol, or port) that a browser should permit loading of resources.

    You can create a fairing to handle CORS globally for your app. For example, the following will allow GET, POST, PATCH, or OPTIONS requests from any origin:

    use rocket::{Request, Response};
    use rocket::fairing::{Fairing, Info, Kind};
    use rocket::http::Header;
    
    pub struct CORS();
    
    impl Fairing for CORS {
        fn info(&self) -> Info {
            Info {
                name: "Add CORS headers to requests",
                kind: Kind::Response
            }
        }
    
        fn on_response(&self, request: &Request, response: &mut Response) {
            response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
            response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, PATCH, OPTIONS"));
            response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
            response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
        }
    }
    

    You just have to attach the fairing like this:

    rocket::ignite().attach(CORS())
    

    You can learn more about CORS Response headers here

提交回复
热议问题