How to create POST request with JSON body using web-sys in WebAssembly?
This example below showing how to make GET request, I need to change opts.method("GET"); to opts.method("POST"); but how can i pass a JSON body to the reqeuest.
let mut opts = RequestInit::new();
opts.method("GET");
opts.credentials(web_sys::RequestCredentials::Include);
let request = Request::new_with_str_and_init(
"http://localhost:8080/api/v1/books",
&opts
).unwrap();
match web_sys::window() {
Some(window) => {
let _res = JsFuture::from(window.fetch_with_request(&request))
.await
.map(|err| web_sys::console::log_1(&format!("{:?}", err)
.into()));
},
None => web_sys::console::log_1(&format!("window is none").into()),
}
You can set the body using
RequestInit::body()
and the required headers usingHeaders::set
. You have to pass anOption<JsValue>
toRequestInit::body()
. To pass a string, you can do:To send a more complex object, you can use serde with
JsValue::from_serde
.