我正在使用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