如何使用 bs-fetch 传递查询字符串参数?

How to pass query string parameters with bs-fetch?

将查询字符串参数传递给 bs-fetch 的正确方法是什么?

目前,我有:

Fetch.fetch("https://example.com/api?param1=value1&param2=value2")

显然,这对于较大的参数列表是不可持续的。

有更好的方法吗?

我不认为有什么内置的东西。 只需制作您自己的查询构建器函数,就像这样

let payload = Js.Dict.empty();

Js.Dict.set(payload, "email", Js.Json.string("email@email.co"));

Js.Dict.set(payload, "password", Js.Json.string("secret"));

let query =
  Js.Dict.keys(payload)
  |> Array.fold_left(
       (query, key) =>
         switch (Js.Dict.get(payload, key)) {
         | Some(value) =>
           query ++ key ++ "=" ++ Js.Json.stringify(value) ++ "&"
         | _ => query
         },
       "?"
     );

这里有一个 link 去游乐场。

re:fetch 支持通过任一方式查询参数

request("https://example.com/api",
  ~queryParams=[
    ("param1", "value1"),
    ("param2", "value2")
  ])
|> fetch;

request("https://example.com/api")
|> Request.param("param1", "value1")
|> Request.param("param2", "value2")
|> fetch;

请注意,该库是实验性的。或者,您可以只滑动 the query builder code,它至少经过了一些实战测试(当列表为空时,@monssef 的实现中有一个细微的错误,而且它也没有进行正确的编码):

[@bs.val] external encodeURIComponent : string => string = "";

let _buildUrl = (url, params) => {
  let encodeParam = ((key, value)) =>
    encodeURIComponent(key) ++ "=" ++ encodeURIComponent(value);

  let params =
      params |> List.map(encodeParam)
             |> String.joinWith("&");

  switch params {
  | "" => url
  | _ => {j|$url?$params|j}
  };
};