【问题标题】:How to I get the body text of a Response object returned by the fetch API in ClojureScript?如何获取 ClojureScript 中 fetch API 返回的 Response 对象的正文?
【发布时间】:2019-11-01 20:04:12
【问题描述】:

我正在尝试使用 Github Gist API 来获取我所有 Gist 的列表,如下所示:

(ns epi.core)

(.then  (.fetch js/window "https://api.github.com/users/seisvelas/gists")
        (fn [data] (.log js/epi data)))

js/epi 只是console.log,除了由我使用的博客平台 (epiphany.pub) 提供。

当我从 curl 调用该 API 时,它工作正常;但是,当在 cljs 中完成而不是给我响应的主体时,这给了我[object Response]。有谁知道我如何获取响应的正文?

【问题讨论】:

    标签: clojure clojurescript fetch-api clojurescript-javascript-interop


    【解决方案1】:

    TL;DR

    (-> (.fetch js/window "https://api.github.com/users/seisvelas/gists")
      (.then #(.json %))  ; Get JSON from the Response.body ReadableStream
      (.then #(.log js/epi %))
    

    是我要写的


    在 ClojureScript 中,可以使用

    调用像 data.body() 这样的 JavaScript 调用
    (.body data)
    

    和一个像data.body这样的JavaScript属性访问

    (.-body data)
    

    其中一个应该适用于您的情况。但是,如果您想要 get JSON from the bodyfetch API 需要更多,我假设您基于端点执行此操作。

    如果您正在处理承诺链,您可能还需要考虑使用->(线程优先),以便从上到下读取。

    有关线程化承诺链的更多信息,请参阅this Gist

    【讨论】:

      【解决方案2】:

      有一个包装 js fetch API 的库,名为 lamdaisland.fetch。该库使用transit作为默认编码格式,因此在使用github API时需要指定accept格式。

      此库包含 kitchen-async.promise 作为其依赖项,因此您可以在 ClojureScript 源代码中要求 kitchen-async.promise。

      (ns fetch.demo.core
        (:require [kitchen-async.promise :as p]
                  [lambdaisland.fetch :as fetch]))
      
      (p/try
        (p/let [resp (fetch/get
                      "https://api.github.com/users/seisvelas/gists"
                      {:accept :json
                       :content-type :json})]
          (prn (:body resp)))
        (p/catch :default e
           ;; log your exception here
          (prn :error e)))
      

      【讨论】:

        【解决方案3】:

        似乎 .fetch 返回一个 Response 对象,您需要从中获取属性 body 用于正文。 https://developer.mozilla.org/en-US/docs/Web/API/Response

        类似(.body data)

        【讨论】:

          猜你喜欢
          • 2021-07-04
          • 2017-03-18
          • 1970-01-01
          • 2015-11-08
          • 2017-04-14
          • 2015-07-28
          • 2020-09-17
          • 2022-11-30
          • 2016-11-17
          相关资源
          最近更新 更多