Add RequestBuilder::fetch_mode_no_cors()

This commit is contained in:
rhysd
2020-01-06 12:54:24 +09:00
committed by Sean McArthur
parent 22fe6566ff
commit 6004623784
4 changed files with 37 additions and 0 deletions

View File

@@ -136,6 +136,7 @@ features = [
"Headers",
"Request",
"RequestInit",
"RequestMode",
"Response",
"Window",
]

View File

@@ -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<Request> {

View File

@@ -120,6 +120,11 @@ async fn fetch(req: Request) -> crate::Result<Response> {
}
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();

View File

@@ -13,6 +13,7 @@ pub struct Request {
url: Url,
headers: HeaderMap,
body: Option<Body>,
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.
///