weixin_33716941 2019-03-21 18:42 采纳率: 0%
浏览 43

JSON错误地被解析

I have 2 js files, one for client and 1 for server. Client enters login data and it gets sent to server. The server checks if user email is found and then checks if password is correct. I am doing an if statement to verify if 'result' is populated, then proceed to checking if password in correct. However I keep on getting this error node.js error, and this, "", gets displayed in my browser. Can you please help me? I have been stuck for days now.

Client.js

var textbox;
var emailtextbox;
var dataDiv;
window.onload = initLogin;

function initLogin(){
    textbox = document.createElement("input");
    textbox.id="textbox";
    emailtextbox = document.createElement("input");
    emailtextbox.id="emailtextbox";
    dataDiv = document.createElement("div");
    var header = document.createElement("h1");
    header.appendChild(document.createTextNode("Select User"));
    var button = document.createElement("BUTTON");
    button.id = "myBtn";
    var textBtn = document.createTextNode("Click me");
    button.appendChild(textBtn);
    button.addEventListener("click", () => {
        SendLoginData();
    });

    var docBody = document.getElementsByTagName("body")[0];//Only one body

   docBody.appendChild(header);
   docBody.appendChild(dataDiv);
   docBody.appendChild(textbox);
   docBody.appendChild(emailtextbox);
   docBody.appendChild(button);
}

function SendLoginData(){
    var email = document.getElementById("emailtextbox").value; //I want to send it to server.js
    var password = document.getElementById("textbox").value;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var dataObj = JSON.stringify(this.responseText);
        dataDiv.innerHTML = dataObj;
    }
};
xhttp.open("GET", "/login/" +password+ "&"+email, true);
xhttp.send();
}

Server.js

 var express = require('express');
 var app = express();
 app.get('/login/*', handleGetRequest); //how do I pass usrName here?
 app.use(express.static('public'));
 app.listen(5000);

 function handleGetRequest(request, response){
     var pathArray = request.url.split("/");
     var processID = pathArray[pathArray.length - 2];
     var pathEnd = pathArray[pathArray.length - 1];
     if(processID === 'register'){
          response.send("{working}");
     }
     else
         var registerArray = pathEnd.split("&");
         searchEmail(registerArray,response);
     }

     function searchEmail(registerArray, response){
     var mysql = require('mysql');
     var con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'customer',
    port: 6000
});
con.connect();
var answer = selectData();
response.send(answer);

//Function that adds test data to database
function selectData(){
    var sql = "SELECT * FROM cust where LastName = '" +registerArray[0]+"'";
    con.query(sql, function (err, result) {
        console.log(JSON.stringify(result)); //correctly displaying stuffs from db
        if (JSON.parse(result).length) { //statement not working correctly.
            var pw = "SELECT ID FROM cust where LastName = '" +registerArray[0]+"'";
            con.query(pw, function (err, result) {
                var idcheck  = JSON.parse(result);
                console.log(result); //always shows undefined
                if (idcheck !== registerArray[1]){
                    return ("{re enter correct password}");
                } else {
                    return ("{login successfully}");
                }
            });

        } else {
            return("{sign up first}");
        }
    });
}
con.end();
  • 写回答

1条回答 默认 最新

  • weixin_33695082 2019-03-21 23:07
    关注

    Try like this:

    var response = JSON.parse(JSON.stringify(result[0]));
    
    if (response.LastName) { 
        var pw = "SELECT ID FROM cust where LastName = '" +registerArray[0]+"'";
        con.query(pw, function (err, result) {
            var idcheck  = JSON.parse(result);
            console.log(result); //always shows undefined
            if (idcheck !== registerArray[1]){
                return ("{re enter correct password}");
            } else {
                return ("{login successfully}");
            }
        });
    } else {
        return("{sign up first}");
    }
    

    If you console.log the result of your query, like this:

    console.log(result[0]);
    

    You will get a RowDataPacket object:

    RowDataPacket { firstName: "My First Name", lastName: "My Last Name" }
    

    That's why you need to first stringify it so it become like this:

    { "firstName": "My First Name", "lastName": "My Last Name" }
    

    And finally you can parse it and check if you got back an user by validating if the LastName property exists. So, all in one line:

    var response = JSON.parse(JSON.stringify(result[0]));
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!