如何生成 JWT 并将其返回到我的应用程序 Angular、Node、Express

How to generate a JWT and get it back to my app Angular, Node, Express

我正在为我的应用构建一些身份验证。现在,我正在发布到创建 JWT 的服务器。我发回令牌,但不确定如何捕获它。我在服务器上使用 Node/Express,在前端使用 Angular。这是端点和 Angular 函数。

app.post('/session', function (req, res, next){
        var username = req.body.username
        // validate password
        var token = jwt.encode({username: username}, secretKey)
        res.json(token)
    })

$scope.login = function (username, password) {
          console.log('submitting to server')
          var creds = {
            username: $scope.username,
            password: $scope.password
          }
          var token = $http.post('http://localhost:3002/session', creds)
          console.log(token)
        }

打印了一个对象而不是令牌。我可以看到令牌正在正确生成,因为我能够将它打印到服务器的控制台并通过邮递员生成一个。

您需要使用 .then()

链接您的 $http
$scope.login = function (username, password) {
          console.log('submitting to server')
          var creds = {
            username: $scope.username,
            password: $scope.password
          }
          $http.post('http://localhost:3002/session', creds)
          .then(function(res){
             // res.data should contain your token
             console.log(res.data) 
           })
        }

要给出更准确的答案...

你非常非常接近,现在你有

    var token = $http.post('http://localhost:3002/session', creds)

这不是将令牌设置为实际令牌,而是将令牌设置为承诺。这很好,这就是你想要做的。

但是,从那以后你必须兑现承诺,你可以做到

    token.then(function(res){
      // res.data should contain your token
      console.log(res.data) 
    })

如前所述,但这里有一个更好的方法...

    var tokenReq = $http.post('http://localhost:3002/session', creds);

    tokenReq.success(function(data) {
      // This will fire when the request is successfull
      // data will contain the response, from there you could
      // find your token
      console.log(data);
    }

    tokentReq.error(function(data) {
      // This will fire if the request is not successfull
      console.log('Something went wrong!', data);
    }

处理各种情况都非常利落。

在谈论 .success 或 .error 等承诺时,我总是感到困惑,我总是问自己,"how in the world does it know it's a success or an error?"

由响应的状态码决定,所以如果你设置状态码为500、404之类的,就会触发.error,200等会触发.success。

编辑:还有一件事,看起来您可能没有发回正确的数据。我可能是错的,但我认为您不能只在 res.json(token) 内发送令牌,我认为它不会有效 JSON。我不想 运行 我的项目要测试,但这就是我所做的...

    var token = createToken(user);
    res.json({
      token: token,
      userData: user
    });