ajaxfetchscala.js

Ajax.post --> dom.fetch


I'm trying to use the dom.fetch (or dom.Fetch.fetch) api instead of Ajax.post and have a few problems:

Is this a correct translation from ajax to fetch?

Ajax.post(
  url = "http://localhost:8080/ajax/myMethod",
  data = byteBuffer2typedArray(Pickle.intoBytes(req.payload)),
  responseType = "arraybuffer",
  headers = Map("Content-Type" -> "application/octet-stream"),
)

dom.fetch(
  "http://localhost:8080/fetch/myMethod",
  new RequestInit {
    method = HttpMethod.POST
    body = byteBuffer2typedArray(Pickle.intoBytes(req.payload))
    headers = new Headers {
      js.Array(
        js.Array("Content-Type", "application/octet-stream")
      )
    }
  }
)

A "ReferenceError: fetch is not defined" is thrown on the js side though, same if replacing with dom.Fetch.fetch.

My setup:

Fresh jsdom 19.0.0 with

npm init private
npm install jsdom

project/plugins.sbt

libraryDependencies += "org.scala-js" %% "scalajs-env-jsdom-nodejs" % "1.1.0"
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.8.0")

build.sbt (in js project)

libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "2.0.0"
jsEnv := new JSDOMNodeJSEnv(JSDOMNodeJSEnv.Config()
  .withArgs(List("--dns-result-order=ipv4first")))

Thought that the jsEnv workaround was not needed on Scala.js 1.8 (see https://github.com/scala-js/scala-js-js-envs/issues/12#issuecomment-958925883). But it is still needed when I run the ajax version. With the workaround, my ajax version works fine, so it seems that my node installation is fine.


Solution

  • The fetch API is only available by-default in browser environments, and not in Node. node-fetch is also not pulled in (or at least not re-exported) by jsdom, so fetch is not available with the current package/environment setup.

    Possible solutions:

    1. Set the ScalaJS side up in such a way that it would call node-fetch on NodeJS and fetch on browser
    2. Use XMLHttpRequest which is available on both platforms

    (Please see the #scala-js channel in the Scala Discord for a related conversation).