我刚刚开始学习,这里有我的代码。我正在尝试从ejs文件创建Ajax请求以处理响应并将令牌写入localStorage。但这行不通。我该怎么办?
实际上,我什至不确定我是否应该将令牌保存在本地存储中。因此,有关授权的任何提示,文章和教程都将非常有用。
这是我渲染的login.ejs:
router.get('/auth/login', (req, res) => {
res.render('main/login.ejs');
});
这是我在auth.js中签名的jwt-token
router.post('/login', (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
const login = req.body.login;
const password = req.body.password;
// Find user by login
User.findOne({ login }).then(user => {
// Check for user
if (!user) {
errors.login = 'User not found';
return res.status(404).json(errors);
}
// Check Password
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User Matched
const payload = { id: user.id}; // Create JWT Payload
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
user,
token: 'Bearer ' + token
});
}
);
} else {
errors.password = 'Password incorrect';
return res.status(400).json(errors);
}
});
});});
这是我的ejs:
<%const form = document.getElementById('form-submit');
form.submit(event => {
event.preventDefault();
const headers = new Headers();
// Tell the server we want JSON back
headers.set('Accept', 'application/json');
// 1.2 Form Data
// We need to properly format the submitted fields.
// Here we will use the same format the browser submits POST forms.
// You could use a different format, depending on your server, such
// as JSON or XML.
const formData = new FormData();
for (let i = 0; i < form.length; ++i) {
formData.append(form[i].name, form[i].value);
}
console.log(formData);
// This is for the purpose of this demo using jsFiddle AJAX Request endpoint
// formData.append('json', JSON.stringify({example: 'return value'}));
// 2. Make the request
// ================================
const url = '/auth/login/';
const fetchOptions = {
method: 'POST',
headers,
body: formData
};
const responsePromise = fetch(url, fetchOptions);
// 3. Use the response
// ================================
responsePromise
// 3.1 Convert the response into JSON-JS object.
.then(function (response) {
return response.json();
})
// 3.2 Do something with the JSON data
.then(function (jsonData) {
console.log(jsonData);
localStorage.setItem("token", jsonData.token);
window.location.href = '/welcome';
})
});%>