2017-07-26 318 views
0

我試圖向Node.js microservice發送AJAX GET請求。該請求應該在頭{'x-access-token': somtoken}和我的要求如下:Ajax GET請求:未在後端收到x-access-token標頭

$.ajax({ 
    type: "GET", 
    url: "http://localhost:3000/api/books", 
    headers: {'x-access-token' : sometoken}, 
    success: function(dataString) { 
     console.log(JSON.stringify(dataString)); 
    }, error: function(error) { 
     console.log(JSON.stringify(error)); 
    } 
}); 

然而,在微服務收到的首標是如下:

{ host: 'localhost:3000', 
connection: 'keep-alive', 
'access-control-request-method': 'GET', 
origin: 'null', 
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36', 
'access-control-request-headers': 'x-access-token', 
accept: '*/*', 
'accept-encoding': 'gzip, deflate, sdch, br', 
'accept-language': 'en-US,en;q=0.8' } 

等時,其發送錯誤響應403

從Postman發送請求時服務正常工作。 我該如何解決這個問題?

+0

您正在查看的請求標題僅適用於飛行前請求...您首先需要讓您的服務在實際請求發生之前正確回答該問題。 – CBroe

+0

聽起來這很可能是您的令牌格式問題,「令牌」看起來像什麼? – James

+0

@CBroe,請您詳細說明一下嗎?爲什麼當我發送Postman的請求時不會發生這種情況? – TamerB

回答

0

添加代碼手工做的POST reauests的工作,但不能與X-訪問令牌

然而GET,我固定它通過使用cores npm package

0

你應該嘗試使用beforeSend鉤從jQuery的

$.ajax({ 
    url: "http://localhost:3000/api/books", 
    type: "GET", 
    beforeSend: function (xhr) { 
    xhr.setRequestHeader('x-access-token', token); 
    }, 
    success: function (dataString) { 
    console.log(JSON.stringify(dataString)); 
    }, error: function (error) { 
    console.log(JSON.stringify(error)); 
    } 
}); 
+0

仍然是一樣的行爲。然而,它不應該是'xhr.setRequestHeader('x-access-token',token);'而不是'xhr.setRequestHeader('x-access-token',token);' – TamerB

+0

@TamerB對我的錯,修改了代碼 –