diff --git a/Cargo.toml b/Cargo.toml index c0235f8..ae61dae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -136,6 +136,7 @@ features = [ "Headers", "Request", "RequestInit", + "RequestMode", "Response", "Window", ] diff --git a/src/async_impl/request.rs b/src/async_impl/request.rs index 47364f7..0e95115 100644 --- a/src/async_impl/request.rs +++ b/src/async_impl/request.rs @@ -353,6 +353,19 @@ impl RequestBuilder { self } + /// Disable CORS on fetching the request. + /// + /// # WASM + /// + /// This option is only effective with WebAssembly target. + /// + /// The [request mode][mdn] will be set to 'no-cors'. + /// + /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode + pub fn fetch_mode_no_cors(self) -> RequestBuilder { + self + } + /// Build a `Request`, which can be inspected, modified and executed with /// `Client::execute()`. pub fn build(self) -> crate::Result { diff --git a/src/wasm/client.rs b/src/wasm/client.rs index 71bb938..d0cbff6 100644 --- a/src/wasm/client.rs +++ b/src/wasm/client.rs @@ -120,6 +120,11 @@ async fn fetch(req: Request) -> crate::Result { } init.headers(&js_headers.into()); + // When req.cors is true, do nothing because the default mode is 'cors' + if !req.cors { + init.mode(web_sys::RequestMode::NoCors); + } + if let Some(body) = req.body() { let body_bytes: &[u8] = body.bytes(); let body_array: Uint8Array = body_bytes.into(); diff --git a/src/wasm/request.rs b/src/wasm/request.rs index e9796d6..598e54d 100644 --- a/src/wasm/request.rs +++ b/src/wasm/request.rs @@ -13,6 +13,7 @@ pub struct Request { url: Url, headers: HeaderMap, body: Option, + pub(super) cors: bool, } /// A builder to construct the properties of a `Request`. @@ -28,6 +29,7 @@ impl Request { url, headers: HeaderMap::new(), body: None, + cors: true, } } @@ -119,6 +121,22 @@ impl RequestBuilder { self } + /// Disable CORS on fetching the request. + /// + /// # WASM + /// + /// This option is only effective with WebAssembly target. + /// + /// The [request mode][mdn] will be set to 'no-cors'. + /// + /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode + pub fn fetch_mode_no_cors(mut self) -> RequestBuilder { + if let Ok(ref mut req) = self.request { + req.cors = false; + } + self + } + /// Constructs the Request and sends it to the target URL, returning a /// future Response. ///