【问题标题】:Fetch Result Return with status code and json data使用状态码和 json 数据获取结果返回
【发布时间】:2019-12-21 14:20:36
【问题描述】:

我有一个调用 API 后端的 fetch API 调用,作为回报,我将获得带有状态码的响应对象。我想做的是基于返回,我想返回带有状态码的 JSON 响应。以便 javascript 的其他部分可以根据状态代码进行操作。我的 fetch 函数如下。

我已经尝试如下,但它返回给定的屏幕截图。它给了我不想得到的承诺价值。

export const createUser = ( posts ) => {
    const apiRoute= "/api/register";
    return window.fetch(`${apiRoute}`, {
       "headers": headers,
       method: "POST",
       body: JSON.stringify(posts)
    }).then(response => ({
        'status' : response.status,
        'data'   : response.json()
    }))
        .catch(error => console.error('Error: ', error))
        ;

}

我知道它可能与这篇文章 (Fetch api - getting json body in both then and catch blocks for separate status codes) 重复,但我不希望我的数据作为承诺返回。相反,我想返回完全构造好的 JSON 数据。

类似的东西。

{status: 400, data: {id:1,name:Hello World}}

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    “它给了我承诺的价值”

    没错,根据documentation

    您需要先解决该承诺,然后再解决外部承诺。

    例如

    .then(response => {
      return response.json().then(data => ({
        status: response.status,
        data
      }))
    })
    

    或者,使用async 函数

    export const createUser = async ( posts ) => {
      const apiRoute= "/api/register";
      try {
        const response = await window.fetch(apiRoute, {
          headers,
          method: "POST",
          body: JSON.stringify(posts)
        })
        return {
          status: response.status,
          data: await response.json()
        }
      } catch (error) {
        console.error('Error: ', error)
        throw error
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多