我试图根据服务器的内容以不同的方式处理服务器响应,但是我什至无法运行与响应数据无关的东西。
这是我在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"));
}
在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 => {})
})
我在做什么错了?
答案 0 :(得分:1)
重新发送状态以完成请求,否则该请求将保持打开状态。在 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
})
})