如何在 reactJS 中使用 await 获得完整响应而不仅仅是 body

How to get full response instead of just body using await in reactJS

我正在使用 request-promise-native 库,我正在尝试从请求中获取完整的响应,而不仅仅是 body,因为响应中有内容 header我需要登录。我知道通常要完成该任务,您会这样做:

request.post(opts).then(function (response) { //response }).catch(function (err) { // error })

但我正在使用 Async/await,所以我的代码看起来像这样:const data = await request.post(opts),但是,这只会 return 响应的 body 我我也想访问 header,我该怎么做?

你可以使用 fetch :

 const response = await fetch(URL, {
                                   method: 'POST',
                                   headers: {
                                             'Accept': 'application/json',
                                             'Content-Type': 'application/json',
                                            }
                             })

然后:

const fromHeader = JSON.parse(response.headers.get('header-name'))

我在 Request 中使用了 resolveWithFullResponse 选项,这解决了问题。例如 resolveWithFullResponse: true