Javascript 将标题添加到 window.location.pathname
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35966526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Header to window.location.pathname
提问by ahrobins
I am setting up authentication for an app. After I make a post request to login, a JSON Web Token is sent in response. I am able to attach this to the header via Ajax. The problem is when using window.location.pathname to redirect after login, since it is not an Ajax request it does not have the token attached to the header. How do I get around this?
我正在为应用程序设置身份验证。在我发出登录请求后,将发送一个 JSON Web 令牌作为响应。我可以通过 Ajax 将其附加到标题。问题是在登录后使用 window.location.pathname 重定向时,因为它不是 Ajax 请求,所以它没有附加到标头的令牌。我该如何解决这个问题?
$.ajaxSetup({
headers: {
'x-access-token': window.localStorage.jwt
}
});
var Auth = {
signup: function () {
console.log('signuppp');
var userSignup = {
username: $('#usernameSignup').val(),
password: $('#passwordSignup').val()
};
console.log(userSignup)
return $.post('/api/users/register', userSignup, function (resp) {
console.log('resp: ',resp);
window.localStorage.setItem('jwt', resp.token);
//does not have x-access-token header
window.location.pathname = '/';
})
},
采纳答案by Francesco Pezzella
Short answer is: you cannot set HTTP headers using window.location
.
简短的回答是:您不能使用window.location
.