Javascript 如何使用来自 jQuery 的 AJAX 请求发送令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35861012/
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:17:44  来源:igfitidea点击:

How to send a token with an AJAX request from jQuery

javascriptjqueryexpressjwtexpress-jwt

提问by larz

I use express-jwt and create my token via jQuery and save it in my localStorage with:

我使用 express-jwt 并通过 jQuery 创建我的令牌并将其保存在我的 localStorage 中:

$.ajax({
  url: "http://localhost:8080/login",
  type: 'POST',
  data: formData,
  error : function(err) {
    console.log('Error!', err)
  },
  success: function(data) {
    console.log('Success!')
    localStorage.setItem('token', data.id_token);
  }
});

I have a protected route in my backend like:

我的后端有一条受保护的路由,例如:

app.get('/upload',jwt({secret: config.secret}), function(req, res) {
  res.sendFile(path.join(__dirname + '/upload.html'));
});

How can I send the token from localStorage with the request header?

如何使用请求标头从 localStorage 发送令牌?

回答by gnerkus

You can set the headers in a $.ajaxrequest:

您可以在$.ajax请求中设置标头:

$.ajax({
  url: "http://localhost:8080/login",
  type: 'GET',
  // Fetch the stored token from localStorage and set in the header
  headers: {"Authorization": localStorage.getItem('token')}
});

回答by ilkerkaran

I use the approach below to cover JWT authentication with the result status types

我使用下面的方法来覆盖 JWT 身份验证与结果状态类型

$.ajax({
  url: "http://localhost:8080/login",
  type: "POST",
  headers: { Authorization: $`Bearer ${localStorage.getItem("token")}` },
  data: formData,
  error: function(err) {
    switch (err.status) {
      case "400":
        // bad request
        break;
      case "401":
        // unauthorized
        break;
      case "403":
        // forbidden
        break;
      default:
        //Something bad happened
        break;
    }
  },
  success: function(data) {
    console.log("Success!");
  }
});

回答by yogihosting

If you are using JWT authentication then this is how you add it to the headers in .ajax() method:

如果您使用的是 JWT 身份验证,那么您可以通过以下方式将其添加到 .ajax() 方法中的标头中:

headers: {
    Authorization: 'Bearer '+token
}

,

,