gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:23 25 4
gpt4 key购买 nike

我正在为我的应用程序构建一些身份验证。现在,我正在发布到创建 JWT 的服务器。我将 token 发回,但我不知道如何捕获它。我在服务器上使用 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)
}

打印一个对象而不是 token 。我可以看到 token 正在正确生成,因为我能够将其打印到服务器的控制台并通过 postman 生成 token 。

最佳答案

给出更准确的答案...

你已经非常非常接近了,现在你已经

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

这不是将 token 设置为实际 token ,而是将 token 设置为 promise 。这很好,这就是您想做的事情。

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

    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 等 Promise 时,总是让我感到困惑的一件事是,我总是问自己,“它到底是如何知道这是成功还是错误?”

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

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

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

关于angularjs - 如何生成 JWT 并将其返回到我的应用程序 Angular、Node、Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com