Search code examples
rustwebassemblywasm-bindgenyewweb-sys

How to make POST request with JSON body using web-sys in WebAssembly?


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()),
    }

Solution

  • You can set the body using RequestInit::body() and the required headers using Headers::set. You have to pass an Option<JsValue> to RequestInit::body(). To pass a string, you can do:

    let mut opts = RequestInit::new();
    opts.method("POST");
    opts.body(Some(wasm_bindgen::JsValue::from_str("[1, 2, 3]")));
    opts.credentials(web_sys::RequestCredentials::Include);
        
    let request = Request::new_with_str_and_init(
        "http://localhost:8080/api/v1/books",
        &opts
    ).unwrap();
    
    request.headers().set("content-type", "application/json");
    
    // send the request
    

    To send a more complex object, you can use serde with JsValue::from_serde.