user9984742
user9984742

Reputation:

Can't get express.js response

I'm trying to handle the server response in different ways depending on its content, but I can't even run things that are unrelated to the response data.

Here is my request in jQuery:

function Register() { var form = $('#signup-form') $.post("http://localhost:3000/register", form.serialize(), (data) => console.log("1")) .done((data) => console.log("2")) .fail((data) => console.log("3")) .always((data) => console.log("4")); }

In Express:

rota.post('/register', (req, res) => {
const name = req.body.name;
const age = req.body.age;
const pass = sha256(req.body.pass);
const request = new sql.Request();
request.query(`SELECT CAST(CASE WHEN EXISTS(SELECT * FROM Usuario WHERE username = '${name}') THEN 1 ELSE 0 END AS BIT) AS re`).then(
    result => {
        if (result.recordset[0].re == true) {
            console.log("usuário já registrado");
            res.send("1");
        } else {
            request.query(`INSERT INTO Usuario(username, userage, userpass) VALUES('${name}', '${age}', '${pass}')`);
        }
    }).catch(result => {})
})

What am I doing wrong?

Upvotes: 1

Views: 41

Answers (1)

Harry Theo
Harry Theo

Reputation: 784

Send status back in order to complete the request or it will remain open. Insert a 400 status response in your catch block to let the front-end know that the request has failed and to enter the fail() function:

request.query(`SELECT CAST(CASE WHEN EXISTS(SELECT * FROM Usuario WHERE username = '${name}') THEN 1 ELSE 0 END AS BIT) AS re`).then(
    result => {
        if (result.recordset[0].re == true) {
            console.log("usuário já registrado");
            res.send("1");
        } else {
            request.query(`INSERT INTO Usuario(username, userage, userpass) VALUES('${name}', '${age}', '${pass}')`);
            res.status(200).send();  // here add a status of 200 to signal success
        }
    }).catch(result => {
       res.status(400).send();  // send also a 400 status response to signal failure
    })
})

Upvotes: 1

Related Questions