簡體   English   中英

獲取響應中未顯示標題

[英]Headers not showing in fetch response

我可以在 Chrome DevTools 中看到標題“x-auth-token”。 在此處輸入圖片說明

但是,標題沒有出現在我的提取響應中。 請協助,以便我可以使用標題數據。

我使用 NodeJS 作為后端 API,使用 ReactJS 作為前端。 這些是我的文件。

NodeJS 中間件 - cors.js

module.exports = function enableCorsSupport(app) {
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, x-auth-token");
    res.header("Access-Control-Expose-Headers", "x-auth-token");
    next();
  })
}

NodeJS 路由 - users.js

router.post('/login', async (req, res) => {

  // NOTE: code left out so post would be smaller

  const token = user.generateAuthToken();
  res.header('x-auth-token', token).send(_.pick(user, ['_id', 'firstName', 'email', 'isAdmin']));
})

ReactJS - 我的獲取請求

fetch('http://localhost:4000/api/users/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.props.email,
      password: this.props.password
    })
  })
  .then(res => {
    console.log('res.headers', res.headers)
    return res.json()
  })
  .then(data => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err)
  })
}

這是在我的成功獲取請求中的 console.log 的 Chrome 控制台中。 標頭響應中的標頭為空。 請指教。 僅供參考,這是用戶測試數據。 在此處輸入圖片說明

Header對象不為空。 它只是不是一個常規對象,因此它的內容沒有作為其實例的屬性。 因此,您不會在 console.log 視圖中看到標題/值。

要獲取特定標頭的值,您需要使用get()方法

var token = response.headers.get('x-auth-token');
console.log(token);

您也可以使用 for ... of

for(const header of response.headers){
   console.log(header);
}

演示

 fetch('https://cors-anywhere.herokuapp.com') .then(res=>{ for(const header of res.headers){ console.log(`Name: ${header[0]}, Value:${header[1]}`); } });

使用 Node.js 我找到了這個解決方案,使用了ExposureHeaders

 const cors = require('cors'); const express = require('express'); // .......... var app = express(); app.use(cors({ exposedHeaders: ['x-auth-token'], }));

對於閱讀,沒關系:

 x_auth_token = res.headers.get('x-auth-token');

公開x-auth-token標頭的另一種方法是

  res
    .header("x-auth-token", token)
    .header("access-control-expose-headers", "x-auth-token")
    .json(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM