How to send html data from node js to front end?

Viewed 3168

I am currently creating an application where I used MongoDB to store login data , nodejs for creating API and front end JS HTML to display the page. I am Creating user where i pass the email id and password via fetch ajax POST call to the backend node server. The backend api route creating the user in DB. I want after creating the user I want to redirect to a different page. How can i do that? her is my code snippet.

//front end fetch call

async function  createUser(email , password) {

return fetch("http://localhost:3000/user", 
    { 

    // Adding method type

    method: "POST", 

    // Adding body or contents to send 

    headers :{
        "content-type": "application/json"
    },

    body: JSON.stringify({
        "userId" : email.value,
        "password" : password.value
    })
});

}

//beckend code

 app.post('/user', async (req, res) => {

// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Methods", "POST,OPTIONS");
const {error} = validate(req.body);

if (error) {
return res.status(400).send(error.details[0].message);
}
let user = await User.findOne({userId : req.body.userId});
if(user) return res.status(400).send("User already registered");

let newUser = new User (
    {
        userId : req.body.userId,
        password : req.body.password
    }
);

newUser = await newUser.save();
res.redirect('/logged');
//res.send(newUser)
//res.send("<h1>Hi</h1>");
//res.sendFile((path.join(__dirname+'/loggedon.html')));
//res.send("<h1>Hi</h1>");
}

);

app.get('/logged' , function(req, res){
    res.send("<h1>Hi</h1>");
    // res.setHeader(200 , 'Content-Type' , 'text/html');
    // fs.readFile('./loggedon.html', function(err , data){
    //     res.write("<h1>Hi</h1>");
    // })

});

I was checking sending only HI. but this will work fine in local server. but how will i send data to Front end. Please let me know. comment lines are the things I already tried.

1 Answers

res.redirect sends an HTTP redirect response which means "You asked for some data from this URL. You can get it from this URL instead".

Since you made the request with Ajax, the redirect will be followed, the new URL requested, and the result passed to the Ajax handler.

You haven't written a handler (or, if you have, you haven't bothered to include it in the question) so nothing happens.


Aside: It is important to note that it does not mean "Load the new URL in the main browser window".

The new URL will only be loaded in the main browser window if the request was intended to be loaded there in the first place.

Yours was not. It is an Ajax request.


You could have the Ajax handler assign a new value to location when the promise resolves.

Frankly, if you want to load a new page, I'd question the use of Ajax in the first place and just design the system to use a regular form submission with no client-side JS involved at all.

Related