美文网首页
我的第一个nodejs全栈程序

我的第一个nodejs全栈程序

作者: 报告老师 | 来源:发表于2018-01-14 13:22 被阅读23次

    用nodejs做一个登陆网站功能,集成后台逻辑,实现页面提供。

    const http = require('http')

    const url = require('url')

    const mysql = require('mysql')

    const dbServer = mysql.createConnection({

    host:'localhost',

    database:'sjh',

    port:'3306',

    user:'root',

    password:'sjh'

    })

    dbServer.connect()

    var login = (id,username,passwd)=>{

    return new Promise((reslove,reject)=>{

      const sql = 'select * from users where username="' + username + '" and passwd="' + passwd + '"'

    dbServer.query(sql,(err,result)=>{

    if (err) {

    reject(err)

    console.error(err)

    return

    }else{

    reslove(result)

    }

    })

    })

    }

    http.createServer((req,res)=>{

    const parseURL = url.parse(req.url,true,true)

    const username = parseURL.query.username

    const pathname = parseURL.pathname

    if (pathname==='/login') {

    const passwd = parseURL.query.passwd

    const id = parseURL.query.id

    const info = {

    id,

    username,

    passwd

    }

    login(id,username,passwd).then((result)=>{

    console.log(JSON.stringify(result))

    console.log(JSON.stringify(info))

    if (JSON.stringify(result).indexOf(JSON.stringify(info))>0) {

    res.end(''+JSON.stringify(result[0]))

    }else{

    res.end('this user is not exist!')

    }

    })

    }else{

    res.end('<h1>404!not found!</h1>')

    }

    }).listen(8800,()=>{

    console.log('8800 is working now....')

    })


    login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
        <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form name="loginform" method="post">
    <input id="id" type="text">
    <input id="usr" type="text" >
    <input id='pwd' type="password">
    <input type="button" value="登录">
    </form>
    <script>
    $('form').click(login)
    function login(res){
    var id = $('#id').val()
    var username = $('#usr').val()
    var passwd = $('#pwd').val()
    $.post('http://192.168.119.150:8880/login?id='+id+'&username='+username+'&password='+passwd)
    }
    </script>
    </body>
    </html>I 

    相关文章

      网友评论

          本文标题:我的第一个nodejs全栈程序

          本文链接:https://www.haomeiwen.com/subject/ekykoxtx.html