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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:26:59  来源:igfitidea点击:

Add Header to window.location.pathname

javascriptjqueryajaxauthenticationjwt

提问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.

Adding http headers to window.location.href in Angular app

在 Angular 应用程序中将 http 标头添加到 window.location.href