weixin_33737774 2015-11-29 18:27 采纳率: 0%
浏览 757

解析xhr.responseText

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

    }
  • 写回答

0条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 macOS使用IDEA 2022.2.4打包JDK6项目报错
      • ¥20 OpenCV-Python简单轮廓寻找
      • ¥20 使用matlab进行含参数的最优化求解及数值模拟
      • ¥20 MATLAB找出一维变量中的局部极大值和局部极小值,并进行运算
      • ¥15 有Chang求三维杆单元几何非线性分析matlab代码
      • ¥50 使用unity easyar录屏功能。录屏视频整体色调很暗
      • ¥50 pyinstaller 打包问题
      • ¥15 无法使用cnssc调取网页数据
      • ¥15 Pycharm安装en_core_web_sm失败出现Could not find a version that satisfies the requirement spacy报错
      • ¥15 Python社区划分