login rest api using express giving HTML content error in postman

I am trying to create a simple login api using node js and express, however postman is giving the following error

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>Cannot GET /login/</pre>
    </body>
</html>

however my signup api is working fine and I can create my user profile and am getting response

code that I have written for login is as follows:

exports.verifyuser = (req, res) => {
    User.findOne({email:req.body.email})
    .then(user => {
        if(!user) {
            return res.status(404).send({
                message:"no user with email id found"
            });            
        }
        res.send(user);
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "Note not found with id "
            });                
        }
        return res.status(500).send({
            message: "Error retrieving note with id "
        });
    });
};

signup api:

// create user
exports.createuser = (req, res) => {
    // Validate request
    if(!req.body.email) {
        return res.status(400).send({
            message: "Email can not be empty"
        });
    }
    // Create a Note
    const note = new User({
        email: req.body.email || "Untitled Email",
        password: req.body.password
    });

    // Save Note in the database
    note.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while creating the profile."
        });
    });
};

routes are as follows:

// create user
   app.post('/signup',cors(),content.createuser);   
    
// verify user
   app.get('/login/:email',cors(),content.verifyuser);

I am very new to express, hence unable to rectify where have I gone wrong. Kindly help me out here.

Answer

The error (from Postman) suggests you tried to access route /verify. But you don’t seem to have a /verify route (your question only shows /signup and /login/:email routes).

Also, in verifyuser, you might need to change this line:

User.findOne({ email: req.body.email })

to:

User.findOne({ email: req.params.email })

This is because the email is captured as a named route parameter (in /login/:email), so should be available under req.params (not req.body). (req.body doesn’t make sense here since the handler is for GET requests, which won’t have a body.)

Once that’s done, restart the server, send a GET request via Postman to something like /login/ABC (just an example) and then see if you get a response like: "no user with email id found".

Leave a Reply

Your email address will not be published. Required fields are marked *