我在服务器(node.js)到客户端(常规js)之间转换数据时遇到问题。 问题在于,当我查看F12时,数据转换得不好。
客户:
//send user name if exist
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/start", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
userName: newUserName,
password: newPassword
}));
//getting info if the user exist or not
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText !== null) { //exist
document.getElementById("exist").style.display = "block";
setTimeout(function () {
document.getElementById('exist').style.display = "none";
}, 3000);
console.log("exist");
} else { //not exist
console.log("not exist");
}
}
};
xhttp.open("POST", "http://localhost:3000/start");
xhttp.send();
服务器:
app.post('/start', function (req, res) {
const userName = req.body.userName;
const userPassword = req.body.password;
//build new user if not exist
User.findOne({ userName: userName }, function (foundUser, err) {
if (foundUser === null) { //the user doesnt exist yet
const newUser = new User({
userName: userName,
userPassword: userPassword,
});
newUser.save();
// res.status(200).send(false); //not exist
console.log("new user");
} else {
console.log("exist");
// res.status(200).send(true); // exist
}
res.status(200).send(foundUser);
console.log(foundUser);
});
});