您处理对的响应不正确
/index
在服务器端路由
更新后端以将其处理为
// Assuming `findUserOne` is a function that searches for a user in your database
app.get('/index', urlencodedParser, async function(req, res) {
let objJson = {};
if (req.query.user_name) objJson.user_name = req.query.user_name;
if (req.query.password) objJson.password = req.query.password;
try {
const result = await findUserOne(objJson);
if (result && result.activate === true) {
const data = await fs.readFileSync('./index.html', 'utf8');
res.set('Content-Type', 'text/html');
res.send(data);
} else {
const data = await fs.readFileSync('./login.html', 'utf8');
res.set('Content-Type', 'text/html');
res.send(data);
}
} catch (error) {
console.error('Error finding user:', error);
res.status(500).send('Internal Server Error'); // Handle error appropriately
}
});
并调整你的客户以了解它
async function entrar() {
const user_name = document.getElementById('user_name').value.trim();
const password = document.getElementById('password').value.trim();
try {
const response = await fetch('/user/search', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const objJson = await response.json();
if (objJson && objJson.user_name === user_name && objJson.password === password) {
localStorage.setItem('objJson', JSON.stringify(objJson));
window.location.href = `/index?user_name=${encodeURIComponent(user_name)}&password=${encodeURIComponent(password)}`;
} else {
window.location.href = '/login';
}
} catch (error) {
console.error('Error fetching data:', error);
window.location.href = '/login'; // Redirect to login page on error
}
}