我在标题中有以下部分(在index.html文件中):
<div class="rightsidetext">
<div class="usernameDisplay" style="display: none;"></div>
<div class="loginbutton" id="signOutButton" style="display: none;">
<a href="#">Sign Out</a>
</div>
<div class="loginbutton"><a href="signin.html">Sign in</a></div>
<div class="loginbutton"><a href="Login.html">Log in</a></div>
</div>
首次加载网站时,会显示登录和登录按钮。用户登录后,我希望将这两个按钮替换为各自的用户名和注销按钮。
在链接到index.html(replaceWithUsername.js)的js文件中,我有:
document.addEventListener('DOMContentLoaded', () => {
const usernameDisplay = document.querySelector('.usernameDisplay');
const signOutButton = document.getElementById('signOutButton');
const signInButton = document.querySelector('.loginbutton a[href="signin.html"]');
const loginButton = document.querySelector('.loginbutton a[href="Login.html"]');
// Retrieve username from localStorage
const username = localStorage.getItem('username');
if (username) {
// Show username and sign out button
usernameDisplay.textContent = username;
usernameDisplay.style.display = 'block';
signOutButton.style.display = 'block';
// Hide sign-in and log-in buttons
signInButton.style.display = 'none';
loginButton.style.display = 'none';
} else {
console.log('No username found');
}
});
在signin.html的末尾我有:
<script>
document.addEventListener('DOMContentLoaded', function() {
const inputField = document.getElementById('wantedSpace');
// Listen for changes in the input field
inputField.addEventListener('input', function(event) {
const username = event.target.value; // Get the value entered by the user
if (response.status == 200) {
console.log('Username found:', username);
// Set username in localStorage
localStorage.setItem('isLoggedIn', true);
localStorage.setItem('username', username);
// Redirect to index.html
window.location.href = '/allPages/index.html';
} else {
console.error('Login failed. Please try again.');
}
});
});
</script>
此外,我还有登录路由(在node.js中,它连接到mongoDB batabase):
app.post('/login', async (req, res) => {
const { usernameOrEmail, password } = req.body;
try {
// Find user by username or email
const user = await User.findOne({ $or: [{ username: usernameOrEmail }, { email: usernameOrEmail }] });
if (!user) {
return res.status(404).redirect('/allPages/registration_feedback/sign_in_feedback/userNotFound.html');
}
// Compare entered password with hashed password
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(401).redirect('/allPages/registration_feedback/sign_in_feedback/incorrectPassword.html');
}
console.log('Loged in user:', user);
const token = generateToken(user);
return res.status(200).redirect('/allPages/index.html');
} catch (err) {
console.error('Login error:', err);
return res.status(500).json({ error: 'Login failed. Please try again.' });
}
});
登录用户后,在 VSC 终端中,我确实获得了该用户的坐标,但在浏览器中,导航栏保持不变(带有登录和登录按钮,没有用户名),并且在控制台中显示以下消息:
no username found replaceWithUsername.js:24
如何让用户名出现在页面上?
问题在于在本地存储中正确设置和检索用户名:用户名必须在成功登录后存储,然后检索以更新index.html中的UI。 JavaScript 代码需要正确隐藏“登录”和“登录”按钮,同时根据此登录状态显示用户名和“退出”按钮。
if (username) {
// Show username and sign out button
usernameDisplay.textContent = username;
usernameDisplay.style.display = 'block';
signOutButton.style.display = 'block';
// Hide sign-in and log-in buttons by selecting their parent divs
signInButton.parentElement.style.display = 'none';
loginButton.parentElement.style.display = 'none';
} else {
console.log('No username found');
}
// other code.