Home > Software design >  400 Bad Request for POST request (Node)
400 Bad Request for POST request (Node)

Time:02-04

I'm trying to sign in but getting 400 Bad Request & "Wrong credentialsss".

app.post("/signin", (req, res) => {

    const {email, password} = req.body;
    db.from ('login').select('*').eq("email", email)
    .then(data => {
        const isValid = bcrypt.compareSync(password, data[0].hash)
        if (isValid) {
            return db.from ('users').select('*')
                .eq ("email", email)
                .then(resp => res.json(resp[0]))
                .catch(err => res.status(400).json("failed to get user"))
        } else {
            res.status(400).json("wrong credentials")
        }
    })
    .catch(err=>res.status(400).json("wrong credentialsss")) // <-- HERE
})

However, when I update the code as below, I can successfully fetch the data. I guess the problem is the middle part but have no idea.

app.post("/signin", (req, res) => {

    const {email, password} = req.body;
    db.from ('login').select('*').eq("email", email)
    .then(data => res.json(data))
    .catch(err=>res.status(400).json("wrong credentialsss"))
})

EDIT: This is what I get from second code

{
"error": null,
"data": [
    {
        "id": 1,
        "hash": "$2a$10$JJ/i0c1bcu/1ZcV8f8DSGOipZUm5FLTGmvEygPjdpny3k0DI9/jrC",
        "email": "[email protected]"
    }
],
"count": null,
"status": 200,
"statusText": "OK"

Tried to log the error

"message": "Cannot read properties of undefined (reading 'hash')",
"error": {}

CodePudding user response:

Sorry, I wanted to comment, but my reputation prevents me. Hence asking this question here. Instead of printing data[0].hash, did you try printing data[0] or data, just to ensure you are getting it in the right format and need no conversions.

CodePudding user response:

Try replacing "data[0].hash" with "data.data[0].hash"

You receive a "data" object in the .then and then need to access the "data" property that contains the array of objects

.then(data => {
        const isValid = bcrypt.compareSync(password, data.data[0].hash)
        if (isValid) {
            return db.from ('users').select('*')
                .eq ("email", email)
                .then(resp => res.json(resp[0]))
                .catch(err => res.status(400).json("failed to get user"))
        } else {
            res.status(400).json("wrong credentials")
        }
    })

  • Related