【问题标题】:Fetch API store custom header value for later use获取 API 存储自定义标头值以供以后使用
【发布时间】:2020-02-03 18:19:46
【问题描述】:

我有以下几点:

let eTag: any 

const request = (method: string) => (basePath: string) => async (path: string, data?: object) => {
  const accessToken = await getAccessToken()
  const opt: any = {
    method,
    headers: {
      Authorization: `Bearer ${accessToken}`,
      ...(data && { eTag })
    },
    ...(data && { body: data }),
  }

  return fetch(`${basePath}${path}`, opt).then(
    res => {
      eTag = res.headers.get('ETag')

      return res.json()
    }
  )
}

我已经设法从客户标题eTag 中获取值,但它似乎没有正确存储它。

关于res.json(),我收到Unexpected end of JSON input 的错误

【问题讨论】:

  • 你能粘贴你的json吗?

标签: javascript fetch-api


【解决方案1】:

res.json() 返回一个promise。所以你需要以下内容:

let eTag: any 

const request = (method: string) => (basePath: string) => async (path: string, data?: object) => {
  const accessToken = await getAccessToken()
  const opt: any = {
    method,
    headers: {
      Authorization: `Bearer ${accessToken}`,
      ...(data && { eTag })
    },
    ...(data && { body: data }),
  }

  return fetch(`${basePath}${path}`, opt).then(
    async res => { //add async keyword
      eTag = res.headers.get('ETag')

      return await res.json() //add await here to return resolved json
    }
  )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多