Javascript 解析xhr.responseText
我在尝试使用xhr.responseText来验证mongo数据库中是否已经存在表单条目时花了很多时间。我正在创建一个POST请求,并将this.body设置为一个易于解析的字符串“ERROR”或“SUCCESS” 但是,我无法以正常使用字符串的方式使用xhr.responseText,即使Javascript 解析xhr.responseText,javascript,ajax,mongodb,reactjs,xmlhttprequest,Javascript,Ajax,Mongodb,Reactjs,Xmlhttprequest,我在尝试使用xhr.responseText来验证mongo数据库中是否已经存在表单条目时花了很多时间。我正在创建一个POST请求,并将this.body设置为一个易于解析的字符串“ERROR”或“SUCCESS” 但是,我无法以正常使用字符串的方式使用xhr.responseText,即使typeof显示它是字符串 下面是我处理请求的api.js。我通过将this.body设置为相关字符串来设置xhr.responseText router.post('/edit', function *(r
typeof
显示它是字符串
下面是我处理请求的api.js。我通过将this.body
设置为相关字符串来设置xhr.responseText
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);
});
}
})
下面是my Edit.js的相关部分,在这里可以发出POST请求
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;
}
}
实现xhr。使用
onreadystatechange
不会给我任何我还不知道的信息。我只需要能够操作我传递到this.body
的数据,因为这是我知道如何传递信息的唯一方法。在发送请求之前,您似乎正在使用responseText。我的意思是你不是,因为当我控制台.log(xhr.responseText)时,它代表了我设置这个.body的任何内容。