0

我的问题是关于使用 Node.JS、ajax 和 mysql 以及下面的代码处理方法。

如果客户端输入正确的密码和用户名,服务器将“true”值返回到我的前端(index.html),如果用户名和密码正确返回“false”并显示消息,页面将重定向到 chat.html 页面。

但是,当我尝试使用相同的代码和用户信息时,有时我得到“错误:结束后写入”,有时我没有,并且出现 chat.html。我想它与异步编程有关,因为我经常使用“response.write”,似乎它们与 fs.readFile() 方法中的那些混合在一起。

我应该如何替换我的代码或如何克服这种情况?由于我是 node.js 的新学习者,这让我很困惑。

var http = require ('http');
var url = require('url');
var fs = require('fs');
var json;
var mysql = require('mysql');


var con = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "123456",
    database: "web-chat",
    timeout:"100ms"
});
   

con.connect(function (err) {
   if (err){
       throw err;
   }

    http.createServer(function (request,response) {

        var q = url.parse(request.url, true);
        var filename = "."+q.pathname;
        var uid = q.query.uid;
        var pass = q.query.pass;

        console.log(filename);

        if (q.pathname == "/" || q.pathname == ""  || q.pathname=="./") {
            filename = "./index.html";
        }


        if (q.pathname == "/login"){

            console.log("id: "+uid," pass:"+pass);


            con.query("SELECT * FROM user_table WHERE user_id='"+uid+"' AND password='"+pass+"'", function (err, result, fields) {
                if (err) throw err;

                //console.log(result[0].user_id);
                console.log(uid);

                if(result==""){                 //LOGIN FAILED
                    response.write("false");
                    return response.end();
                }
                else {                  //LOGIN SUCCESSFUL
                    response.write("true");
                    return response.end();
                }

            });
        }

        fs.readFile(filename, function (err, data) {

            if(err){
                console.log("false");
                response.writeHead(404,{'Content-Type':'text/html'});
                return response.end();
            }else{
                console.log("true");
                response.writeHead(200,{'Content-Type':'text/html'});
                response.write(data);
                return response.end();
            }

        });

    }).listen(1337);

});
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #frame-div{
            border: lightgray solid 1px;
            border-radius: 3px;
            width: 40%;
            margin: auto;
        }
        body{
            font-family: Calibri;
        }
        .label{
            display: table-cell;
            padding-top: 15px;
            padding-bottom: 5px;
        }
        .table{
            display: table;
        }
        .table-row{
            display: table-row;
        }
    </style>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="frame-div" class="table">

    <div class="table-row">


        <div class="label">Kullanıcı Adı:</div>
        <div class="label"><input id="user-id" type="text"></div>

    </div>
    <div class="table-row">

        <div class="label">Parola:</div>
        <div class="label"><input id="password" type="password"></div>

    </div>
    <div class="table-row">

        <div class="label">
            <input type="button" value="Giriş Yap" onclick="Login()">
            <form action="registration.html" style="display: inline-block">
                <input type="submit" value="Üye Ol">
            </form></div>

    </div>

</div>

<p id="content"></p>

<script>

    function Login() {
        var userId=document.getElementById("user-id").value;
        var password=document.getElementById("password").value;
        var xhttp;


        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {

            if(this.readyState == 4 && this.status == 200){

                var isregisteredUser=this.responseText;

                console.log("reg user:"+isregisteredUser);

                //console.log(this.responseText.uid);

                if(isregisteredUser=='true'){
                    window.location.href='chat.html?uid='+userId;
                }else
                {
                    document.getElementById("content").innerHTML += "<br/>"+"Hatalı Kullanıcı Adı/Parola";
                }
            }
        };

        xhttp.open("GET","login?uid="+userId+"&pass="+password,true);
        xhttp.send();
    }

</script>

</body>
</html>

我有时得到的错误代码,有时我没有使用相同的代码:

events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: write after end
at write_ (_http_outgoing.js:622:15)
at ServerResponse.write (_http_outgoing.js:617:10)
at Query.<anonymous> (C:\Node JS Projects\Web Chat App\server.js:53:30)
at Query.<anonymous> (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\Connection.js:502:10)
at Query._callback (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\Connection.js:468:16)
at Query.Sequence.end (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
at Query.EofPacket (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
at Protocol._parsePacket (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Node JS Projects\Web Chat App\node_modules\mysql\lib\protocol\Parser.js:76:12)
4

1 回答 1

1

if (q.pathname == "/login"){然后你进入分支,当你得到 MySQL 的响应时,你写一些内容return response.end();

对于任何路径名,即使是上面的路径名,您也可以调用fs.readFile,然后在获取数据时编写一些内容并return response.end();

你需要一个if/else不是if-then-do-it-anyway。

于 2018-12-02T22:24:21.590 回答