I'm having a hell of a time trying to use xhr.responseText to verify whether a form entry already exists in a mongo database. I'm creating a POST request, and am setting this.body to an easily-parseable string "ERROR" or "SUCCESS".
However, I'm not able to use the xhr.responseText in any way that I would normally be able to use a string, even though typeof
shows that it's a string
Below is my api.js which is handling the request. I'm setting the xhr.responseText by setting this.body
to the relevant String.
router.post('/edit', function *(req, res, next) {
console.log(this.request.body);
let {url, links} = this.request.body
let obj = yield linkrSchema.findOne({urlExt: url})
//if that entry already exists
if (obj !== null){
this.body = "ERROR";
}
else{
this.body = "SUCCESS";
linkrSchema.createLinkr(url, 'testuser', links, function(err, linkr){
console.log(err, linkr);
});
}
})
Below is the relevant part of my Edit.js, where the POST request is made.
else{
var xhr = new XMLHttpRequest(); // new HttpRequest instance
xhr.open("POST", "/edit");
xhr.addEventListener("load", e => {
console.log(xhr.responseText)
});
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
console.log(xhr.responseText === "ERROR"); //false
console.log(xhr.responseText); //ERROR
var res = xhr.responseText.match(/ERROR/); //null
alert(res)
if (xhr.responseText === "ERROR") { //never gets here :(
alert(xhr.responseText);
}
else{
xhr.send(JSON.stringify(this.state));
console.log(this.state)
window.location.href = "/" + this.state.url;
}
}