【问题标题】:Express response.send() object not received by JavaScript fetch() ... why?JavaScript fetch() 未收到 Express response.send() 对象...为什么?
【发布时间】:2020-12-23 10:47:41
【问题描述】:

来自 Express response.send 的文档允许在正文中发送对象,我发送如下:

  DBM.saveArticle(obj).then((val) => {
    console.log(val); // verified here
    res.send(val);
    res.end();
    // ... clip here

但是在客户端我没有得到对象。这是在 CRUD 中创建的,我正在使用 fetch POST 来实现这一点。

    // ... snip
    const options = { 
      headers: {'Content-Type': 'application/json'}, 
      method: 'POST', 
      body: JSON.stringify(this.state)
    };    
    fetch("/articles/add", options)
      .then((response) => {
        console.log('DEBUG: Article Added: ', response); // nothing found here in response
        this.props.dispatch({type: 'addArticle', component_state: state});
      })
      .catch((error) => {
        console.log('fetch/POST error', error);
      });
      // ... snip

上面的console.log看起来像这样,这是一张图片,据我所知,它是空的。

响应对象很大,我试图点击它的所有内容,但我可能错过了一些东西。

JavaScript 获取响应对象的官方文档是here on MDN

【问题讨论】:

    标签: javascript reactjs express fetch


    【解决方案1】:

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects

    这只是一个 HTTP 响应,而不是实际的 JSON。为了从响应中提取 JSON 正文内容,我们使用 json() 方法(在 Body mixin 上定义,由 Request 和 Response 对象实现。)

    https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream

    Fetch API 通过提供 ReadableStream 的具体实例 Response 对象的 body 属性。

    fetch 将正文作为 ReadableStream 返回以将其转换为 JSON 使用 response.json()

    fetch('https://example.com/profile', {
      method: 'POST', // or 'PUT'
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    .then(response => response.json())   // << this will convert the response to JSON object
    .then(data => {
      console.log('Success:', data);
    })
    .catch((error) => {
      console.error('Error:', error);
    });
    

    ReadableStream 中的数据在不消费流的情况下是无法访问的,它存储在较低级别的 I/O 源中,称为底层源,底层源有两种类型:推送源和拉取源。

    在 HTTP 请求的情况下,它是 TCP 套接字形式的推送源,其中数据不断从操作系统级别推送,一旦您获得锁和数据,消费者(您的代码)就可以访问数据开始阅读吧,这正是 json() 方法为您做的。

    更多详情请参考https://streams.spec.whatwg.org/#rs-model

    【讨论】:

    • 响应主体是一个流,所以不,你看不到它,不消费它,这就是.json() 会做的事情
    • 我搜索了 ReadableStream here on MDN doc for fetch(),但什么也没找到。
    猜你喜欢
    • 2020-03-05
    • 2020-09-18
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2020-11-18
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多