0

My question is about handling methods using Node.JS, ajax and mysql with the code below.

If the client enters the correct password and username, the server returns "true" value to my front-end (index.html) and the page redirects to chat.html page if username and password correct returns "false" and a message shown.

However, when I try with the same code and user info, sometimes I got "Error: write after end" and sometimes I don't and chat.html appears. I suppose it is related to async programming since I use "response.write" a lot, it seems that they are mixed with the ones in fs.readFile() method.

How should I replace my codes or how can I overcome this situation? Since I am a new learner of node.js it is pretty confusing for me.

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>

Error code that I got sometimes and sometimes I don't with the same code:

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)

1 Answer 1

1

if (q.pathname == "/login"){ then you enter the branch and when you get a response from MySQL you write some content return response.end();

For any pathname, even the one above, you call fs.readFile and then when you get the data you write some content and return response.end();

You need an if/else not an if-then-do-it-anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

Everything is crystal clear now, thanks. I needed to add also else if(q.pathname=="/chat.html"){ for client to see the chat html. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.