登录应用中EJS视图无法渲染问题求助
Hey there! Let's break down why your EJS view isn't showing up after a successful sign-in, even though your fetch request goes through. I've gone through your code and found a couple of key issues that are blocking the page from updating.
The Core Problem
Your server is correctly rendering the signinsuccess EJS template when login credentials are valid, but your frontend isn't doing anything with the HTML response from the fetch request. Right now, you're sending the request but ignoring the result—so the page never updates.
Step-by-Step Fixes
1. Update Frontend Fetch Logic to Handle the HTML Response
Modify your obj.js code to process the server's response. When sign-in succeeds, we'll take the returned HTML and replace the current page content with it. For error cases (like wrong password), we'll parse the JSON error and show a message to the user:
const form = document.getElementById('Signinform'); form.addEventListener('submit', Signin); async function Signin(event){ event.preventDefault(); const email = document.getElementById('email').value const password = document.getElementById('password').value try { const result = await fetch('/user/signin',{ method:'POST', headers:{ 'Content-Type':'application/json', 'Accept': 'text/html' }, body:JSON.stringify({ email, password }) }); // Handle error responses (like invalid password) if (!result.ok) { const errorData = await result.json(); alert(errorData.message); // Or display this in a dedicated error element on your page return; } // For successful sign-in, replace page content with the rendered EJS HTML const successHtml = await result.text(); document.body.innerHTML = successHtml; } catch (err) { console.error('Sign-in error:', err); alert('Something went wrong during sign-in. Please try again.'); } };
2. Add Proper HTTP Status Codes to Server Error Responses
Right now, all your error responses use a 200 OK status code (the default), which makes it hard for the frontend to tell success and failure apart. Let's update your User.js sign-in route to send appropriate status codes for errors:
// Signin router.post('/signin', async(req,res)=>{ let{email, password}=req.body; email = email.trim(); password = password.trim(); if(email == "" || password == ""){ // 400 = Bad Request (empty inputs) res.status(400).json({ status:"FAILED", message:"Empty Credentials supplied" }); }else{ user.find({email}) .then(data =>{ if(data.length){ const hashedPassword = data[0].password; bcrypt.compare(password,hashedPassword).then(result=>{ if(result){ res.render('signinsuccess',{name : data[0].name}); }else{ // 401 = Unauthorized (wrong password) res.status(401).json({ status: "FAILED", message: "Invalid password entered" }); } }) .catch(err=>{ // 500 = Internal Server Error res.status(500).json({ status: "FAILED", message:"An error occured while comparing passwords" }) }) }else{ // 404 = Not Found (user doesn't exist) res.status(404).json({ status:"FAILED", message:"Invalid Credentials entered" }) } }) .catch(err=>{ console.log(err); res.status(500).json({ status:"FAILED", message:"An error occurered while checking for existing user" }) }) } })
3. (Optional) Consider a Simpler Form Submission Approach
If you don't need AJAX-style fetch behavior, you could skip the fetch entirely and use a standard form submission:
- Add
action="/user/signin"andmethod="POST"to your<form>element - Make sure your input fields have
name="email"andname="password"attributes - Add the urlencoded middleware to your
server.jsto parse form data:app.use(express.urlencoded({ extended: true }));
This way, the browser will automatically handle navigating to the rendered EJS page on success, and you won't need the fetch logic at all.
Why This Works
- The updated fetch code now listens for the server's response: if it's successful, it replaces the current page with the
signinsuccessHTML. If it's an error, it shows the error message to the user. - Adding proper status codes makes it easy for the frontend to distinguish between successful and failed requests, so you can handle each case correctly.
Give these changes a try, and your EJS view should render as expected after a successful sign-in!
内容的提问来源于stack exchange,提问作者SENA rajaguru

