首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用node.js、ajax和mysql处理异步编程中的方法?

如何使用node.js、ajax和mysql处理异步编程中的方法?
EN

Stack Overflow用户
提问于 2018-12-02 22:18:47
回答 1查看 55关注 0票数 0

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

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

然而,当我尝试使用相同的代码和用户信息时,有时我会得到“错误:在结束后写”,有时我没有得到,chat.html出现了。我认为它与异步编程有关,因为我经常使用"response.write“,似乎它们与fs.readFile()方法中的混合。

我应该如何替换我的代码,或者如何克服这种情况?因为我是node.js的新学习者,这对我来说很令人困惑。

代码语言:javascript
复制
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);

});
代码语言:javascript
复制
<!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>

有时和有时不使用相同代码的错误代码:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-02 22:24:21

if (q.pathname == "/login"){然后输入分支,当您从MySQL获得响应时,您将编写一些内容return response.end();

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

无论如何,你需要的是if/else,而不是if

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53585143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档