简体   繁体   English

无法获得 express.js 响应

[英]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:这是我在 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?我究竟做错了什么?

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:catch 块中插入400状态响应,让前端知道请求失败并进入fail()函数:

 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 }) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM