2017-09-25 89 views
1

我需要訪問服務器端(Node)中的axios標頭授權令牌,顯示未定義。請幫助..節點服務器無法檢索反應axios請求標頭參數的值

客戶端(反應)要求:

var config = { 
     headers: { 
      'cache-control':'no-cache', 
      'content-type': 'application/x-www-form-urlencoded', 
      'authorization' :'bearer '+Auth.getToken() 
      } 
     }; 
    axios.get(ApiConfig.API_BASE+'api/admin/profile/', config).then(function(response) { 
     this.setState({status:'success', profile: response.data.data}); 
    }).catch(function(response) { 
     console.log(response); 
    }); 

服務器端(節點):

module.exports = (req, res, next) => { 

console.log(req.headers.authorization); 

    if(!req.headers.authorization) { 
    return res.status(401).end(); 
    } 
}; 

日誌顯示不明確的。我還安慰了整個頭部,但它們的輸出是:

{ host: 'localhost:8027', 
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0', 
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
    'accept-language': 'en-US,en;q=0.5', 
    'accept-encoding': 'gzip, deflate', 
    'access-control-request-method': 'GET', 
    'access-control-request-headers': 'authorization,cache-control', 
    origin: 'http://localhost:3001', 
    connection: 'keep-alive' } 

如何獲取授權令牌值?

謝謝。

+0

[如何從請求中使用NodeJS連接提取請求http頭]可能的重複(https://stackoverflow.com/questions/13147693/how-to-extract-request-http-headers-from-a-request -using-nodejs-connect) – mersocarlin

回答

0

我假設你使用快遞。如果是這樣,請不要將標頭值設爲req.headers.authorization,請嘗試req.get('authorization')

http://expressjs.com/en/api.html#req.get

+0

不工作,console.log(req.header('authorization'));仍然顯示未定義。 –

+0

您使用哪種版本的快遞? – mersocarlin

+0

版本:[email protected] –

-1

如果你是一個跨源的HTTP請求,請確保CORS已經在服務器中啓用。如果您使用快遞cors中間件可以使用。

我想你的問題在於,因爲CORS尚未啓用,你的服務器將首先收到一個OPTIONS請求,所以你的控制檯的整個頭是來自OPTIONS請求,而不是你想要的GET請求。您可以使用console.log(req.method)進行驗證。 BTW req.headers.authorization可以接收標題。

+0

console.log(req.method);顯示「選項」和req.headers.authorization仍未定義。 –

+0

您是否在服務器上啓用了CORS? – movier

+0

是的,這是我的本地主機。我設置了app.use(function(req,res,next)res.header(「Access-Control-Allow-Origin」,「*」); res.header(「Access-Control-Allow-Headers」 ,'Origin,X-Requested-With,Content-Type,Accept,Authorization'); res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS'); next (); }); –