我有一个身份验证API,当我发出登录请求(http://localhost:3001/api/users/login)时会响应令牌。
//Login
router.post('/login', async (req, res) => {
//Validate data before we use
const { error } = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message)
//Checking if the email exists
const user = await User.findOne({
email: req.body.email
})
if (!user) return res.status(400).send('Email or password dont match')
//Password is correct
const validPass = await bcrypt.compare(req.body.password, user.password)
if (!validPass) return res.status(400).send('Invalid password')
//Create and assign a token
const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
res.header('auth-token', token).send(token)
})
我想使用Jquery从前端的const令牌中获取该数据到本地存储中。所以我注册了我的用户。
$('#button-click').click(function () {
$.ajax(
{
type: "POST",
url: 'http://localhost:3001/api/user/register',
data: JSON.stringify({
"name": $("#name").val(),
"email": $("#email").val(),
"password": $("#password").val()
}),
error: function (e) {
console.log(e)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
}
)
})
但是我不知道如何获取这些数据,有人可以帮助我吗?
答案 0 :(得分:1)
您可以像提供错误功能一样提供成功功能。请求成功时将调用此函数。
$.ajax({
...,
success: function(data, status, jqXHR) {
//do stuff with data
},
...
});
答案 1 :(得分:0)
成功用于处理来自api的响应
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost:8080/api/user",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status, jqXHR) {
alert(data);
localStorage.setItem('token', data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("error" + error.responseText);
}
});
有关更多详细信息-https://api.jquery.com/jQuery.ajax/
有关本地存储的更多详细信息-https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
希望它会有所帮助:)
答案 2 :(得分:0)
只需添加成功事件并将响应令牌存储在本地存储中,然后以所需的方式使用令牌即可。
$('#button-click').click(function () {
$.ajax(
{
type: "POST",
url: 'http://localhost:3001/api/user/register',
data: JSON.stringify({
"name": $("#name").val(),
"email": $("#email").val(),
"password": $("#password").val()
}),
error: function (e) {
console.log(e)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, jqXHR) {
localStorage.setItem("app_token", data.token);
},
}
)
})