2016-03-08 29 views
17
与AJAX请求发送令牌

我用快递,智威汤逊和通过jQuery创建我的令牌,并将其与保存在我的localStorage:如何从jQuery的

$.ajax({ 
    url: "http://localhost:8080/login", 
    type: 'POST', 
    data: formData, 
    error : function(err) { 
    console.log('Error!', err) 
    }, 
    success: function(data) { 
    console.log('Success!') 
    localStorage.setItem('token', data.id_token); 
    } 
}); 

我有我的后端就像一个受保护的路径:

app.get('/upload',jwt({secret: config.secret}), function(req, res) { 
    res.sendFile(path.join(__dirname + '/upload.html')); 
}); 

我该如何使用请求头从localStorage发送令牌?

回答

22

您可以设置在$.ajax请求头:

$.ajax({ 
    url: "http://localhost:8080/login", 
    type: 'GET', 
    // Fetch the stored token from localStorage and set in the header 
    headers: {"Authorization": localStorage.getItem('token')} 
}); 
+0

你为什么令牌发送到头?为什么不把数据? – ahmedbhs

+0

@ahmedbhs我相信他试图以某种方式保护令牌。 –

+4

为JWT头,这为我工作'头:{“授权”:'承载'+令牌}' – user326608