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

我正在为我的应用程序build立一些authentication。 现在,我将发布到创buildJWT的服务器上。 我发回令牌,但我不知道如何捕捉它。 我在服务器上使用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) } 

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

给一个更精确的答案…

你非常非常亲密,现在你有

  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); } 

处理所有情况非常整洁。

有一件事总是让我感到困惑,当谈到成功或失败的承诺时,我总是问自己,“这个世界怎么知道这是成功还是错误呢?

这是由响应的状态代码决定的,所以如果你设置状态码为500,404或类似的东西,它会触发.error,200等触发.success。

编辑 :还有一件事,看起来有可能你没有发回正确的数据。 我可能是错的,但我不认为你可以只发送res.json(令牌)里面的令牌,我不认为这将是有效的JSON。 我不想运行我的项目来testing,但这是我做的…

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

你需要链接你的$ http与.then()

 $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) }) }