Cannot read properties of undefined (reading 'fetc...
# workers-help
m
I'm trying to write a worker in Rust with the worker crate. I'm using the fetch API via the service worker global scope:
Copy code
async fn request_sendgrid(api_key: &str, data: String) -> Result<u16, NetworkError> {
    let mut opts = RequestInit::new();
    opts.method("POST");
    opts.mode(RequestMode::Cors);
    opts.body(Some(&JsValue::from_str(&data)));

    let request = FetchRequest::new_with_str_and_init(&"https://api.sendgrid.com/v3/mail/send", &opts)?;

    request
        .headers()
        .set("Authorization", &format!("Bearer {}", api_key))?;
    request.headers().set("Content-Type", "application/json")?;

    let worker_global_scope = js_sys::global().dyn_into::<web_sys::ServiceWorkerGlobalScope>()?;
    let resp_value = JsFuture::from(worker_global_scope.fetch_with_request(&request)).await?;
    assert!(resp_value.is_instance_of::<FetchResponse>());
    let response: FetchResponse = resp_value.dyn_into()?;

    Ok(response.status())
}
The problem now is when running this, fetching the WASM fails with the above error at `build/worker/shim.mjs:181:20`:
Copy code
function fetch(req, env, ctx) {
  const ret = wasm.fetch(addHeapObject(req), addHeapObject(env), addHeapObject(ctx));
  return takeObject(ret);
}
k
What version is the
worker
crate?
You also don't need to do all of that
js_sys
stuff - the Worker crate provides the
fetch
API already