我正在使用XHR請求調用我的後端。這裏是我的前端代碼:Express res.redirect()返回HTML而不是重定向
var makeRequest = function(method, url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.open(method, url);
xhr.send();
}
document.getElementById('button').addEventListener('click', function() {
makeRequest('GET', '/spotify', console.log);
});
這裏是爲/spotify
路線我的後端代碼:
const Querystring = require('querystring');
module.exports = (req, res) => {
const queries = Querystring.stringify({
client_id: process.env.SPOTIFY_ID,
response_type: 'code',
redirect_uri: 'http://localhost:3000/redirect'
});
res.redirect(`https://accounts.spotify.com/authorize?${queries}`);
};
而不是重定向,頁面的HTML被重定向到從XHR函數返回。如果我沒有點擊按鈕(通過像localhost:4000/spotify
之類的東西)去路線,它的工作原理是我想要的,並且我被重定向。
任何想法爲什麼會發生這種情況?
似乎你在這裏使用反引號? => res.redirect('https://accounts.spotify.com/authorize?$ {queries}'); –
這可能會造成什麼區別?試用沒有,並得到相同的行爲。 –
@DavidR - [這不是問題](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals) – Quentin