?注冊接口
注冊接口,用戶提供必要的注冊信息(如用戶名和密碼),服務(wù)器對用戶進行驗證并創(chuàng)建用戶賬號
// 注冊接口
app.post('/register', async (req, res) => {
try {
const { username, email, password } = req.body;
// 檢查用戶名和郵箱是否已被注冊
if (users.some(user => user.username === username)) {
return res.status(400).json({ error: '用戶名已被注冊' });
}
if (users.some(user => user.email === email)) {
return res.status(400).json({ error: '郵箱已被注冊' });
}
// 使用bcrypt對密碼進行哈希處理
const hashedPassword = await bcrypt.hash(password, 10);
// 創(chuàng)建新用戶對象
const user = {
id: Date.now().toString(),
username,
email,
password: hashedPassword
};
// 將用戶信息存儲到數(shù)據(jù)庫
users.push(user);
// 創(chuàng)建訪問令牌
const token = jwt.sign({ userId: user.id }, 'secretKey');
res.status(201).json({ message: '注冊成功', token });
} catch (error) {
res.status(500).json({ error: '注冊失敗' });
}
});
登錄接口
登錄接口,用戶提供登錄憑據(jù)(如用戶名和密碼),服務(wù)器驗證憑據(jù)的正確性并頒發(fā)訪問令牌
app.post('/login', (req, res) => {
// 獲取登錄憑據(jù)
const { username, password } = req.body;
// 在此處進行用戶名和密碼的驗證,如檢查用戶名是否存在、密碼是否匹配等;驗證成功,頒發(fā)訪問令牌;
const token = createAccessToken(username);
// 將訪問令牌寫入 Cookie
res.cookie('token', token, {
httpOnly: true,
secure: true, // 僅在 HTTPS 連接時發(fā)送 Cookie
sameSite: 'Strict' // 限制跨站點訪問,提高安全性
});
// 返回登錄成功的響應(yīng)
res.status(200).json({ message: '登錄成功' });
});
校驗接口?
校驗登錄狀態(tài),服務(wù)器將校驗請求中的登錄憑據(jù)(Cookie 或訪問令牌)的有效性
app.get('/protected', (req, res) => {
// 從請求的 Cookie 中提取訪問令牌
const token = req.cookies.token;
// 或從請求頭部中提取訪問令牌,如果采用前端存儲和發(fā)送訪問令牌方式;示例代碼,需根據(jù)實際情況進行解析 const token = req.headers.authorization.split(' ')[1];
// 檢查訪問令牌的有效性
if (!token) {
return res.status(401).json({ error: '未提供訪問令牌' });
}
try {
// 驗證訪問令牌
const decoded = verifyAccessToken(token);
// 在此處進行更詳細(xì)的用戶權(quán)限校驗等操作
// 返回受保護資源
res.status(200).json({ message: '訪問受保護資源成功' });
} catch (error) {
res.status(401).json({ error: '無效的訪問令牌' });
}
});
前端存儲和發(fā)送訪問令牌
// 從存儲中獲取訪問令牌
const token = localStorage.getItem('token');
// 設(shè)置請求頭部
const headers = {
'Authorization': `Bearer ${token}`
};
// 發(fā)送請求時,手動設(shè)置請求頭部
fetch('/protected', { headers });
使用前端的?localStorage
?來存儲訪問令牌,并在發(fā)送請求時手動設(shè)置了請求頭部的?Authorization
?字段。文章來源:http://www.zghlxwxcb.cn/news/detail-835003.html
注意:無論使用哪種方式,都需要在服務(wù)器端進行訪問令牌的驗證和安全性檢查,以確保請求的合法性和保護用戶數(shù)據(jù)的安全。文章來源地址http://www.zghlxwxcb.cn/news/detail-835003.html
到了這里,關(guān)于Express.js實現(xiàn)注冊和登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!