Node.js 使用expresss,ejs模板引擎实现简单的登录注册

express下如何使用ejs模板引擎 :

    1-安装ejs

    2-express下不需要导入ejs  只需要配置模板引擎 app.set("view engine","ejs")

    3-在服务器下创建模板引擎

             模板引擎的默认路径 views  在该目录下创建ejs模板文件

    4--使用render方法进行ejs模板文件的渲染

            render( "xxx.ejs" , {数据} )

 如何更改模板引擎的默认路径 :

        app.set( "views" , __dirname + "/" + "static" )

 express服务器下配置ejs模板文件的静态资源目录

        app.use( express.static( "public" ) )

基础搭建express服务器:

/* 使用express搭建服务器 */
const express = require("express")

//创建express对象 
const app = express()

//配置ejs模板引擎
app.set("view engine","ejs")

//更改模板引擎的默认路径
app.set( "views" , __dirname + "/" + "static" )
 
//配置静态资源目录
app.use( express.static( "public" ) )


//配置路由 express 支持多种请求方式 get post  put delete  patch head...
app.get("/home",(req,res)=>{
    res.render("home",{
        name : "张三",
        age : 19
    })
})

//配置端口号
app.listen(3000,()=>{
    console.log("服务器已启动,端口号为3000");
})

登录注册:

        注册需要获取前端的数据,注册get请求, 使用res,query 就可以获取前端通过get请求注册的数据信息。

        登录,是post请求 ,需要安装 body-parser, npm i body-parser, 使用创建的服务器,app.use(body-parse),  这时候可以使用req.body 获取前端通过post请求登录的数据信息。

具体代码实现

        express服务器代码:

const url =  require("url")
const fs = require("fs")
const bodyParser = require("body-parser")
// 使用express创建服务器
const express = require("express")

// 创建express对象
const app = express()
app.use(bodyParser())
//配置ejs模板引擎
app.set("view engine","ejs")

//更改模板引擎的默认路径
// app.set( "views" , __dirname + "/" + "static" )
 
//配置静态资源目录
// app.use( express.static( "public" ) )

//配置路由 express 支持多种请求方式 get post  put delete  patch head...
app.get("/home",(req,res)=>{
    res.render("home")
})
//注册页面
app.get("/config",(req,res)=>{
    res.render("config")
})
//点击注册get请求收集账号密码
app.get("/zhu",(req,res)=>{
    let data = req.query
    let datapath = JSON.parse(fs.readFileSync("./data.json"))
    console.log(datapath)
    //判断用户名是否唯一
    if(datapath.some(item => item.username == data.username )){
        res.end("该用户名已经存在")
    }else{
        datapath.push(data)
        fs.writeFileSync("./data.json",JSON.stringify(datapath))
        res.end("成功")
    }
})

//登录接口
app.get("/login",(req,res)=>{
    res.render("login")
})
//点击登录请求接口
app.post("/deng",(req,res)=>{
    let data = req.body
    let pathdata = JSON.parse(fs.readFileSync("./data.json"))
    let one =  pathdata.find(item=> item.username == data.username )
    if(one){ //判断用户名是否存在
        if(data.password == one.password){ //验证密码是否正确
            res.send("登录成功")
        }else{
            res.send("密码不正确")
        }
    }else{
        res.send("没有此账号")
    }
    
})
//配置端口号
app.listen(3000,()=>{
    console.log("服务器已经启动")
})

ejs模块部分:

        注册:

                

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>注册页面</h1>
    <form action="/zhu" method="get">
        <input type="text" name="username" placeholder="请输入用户名">
        <input type="text" name="password" placeholder="请输入密码">
        <input type="submit" value="注册">
    </form>
</body>
</html>

        登录:

                

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>登录页面</h1>
    <form action="/deng" method="post">
        <input type="text" name="username" placeholder="请输入用户名">
        <input type="text" name="password" placeholder="请输入密码">
        <input type="submit" value="登录">
    </form>
</body>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/*模拟STM32设备向EMQ发送数据 */ const mqtt = require('mqtt'); const host = 'iot-06z00cad6kypevk.mqtt.iothub.aliyuncs.com' const port = '1883' const clientId = `iqfzjbFKlyh.js_node_one|securemode=2,signmethod=hmacsha256,timestamp=1685192902891|` const connectUrl = `mqtt://${host}:${port}` const client = mqtt.connect(connectUrl, { clientId, clean: true, connectTimeout: 4000, username: 'js_node_one&iqfzjbFKlyh', password: 'f4cf365e0ed0a68ef9eff1ce571f959a66b1bc9a9970174cd55203e94975b4d2', reconnectPeriod: 1000, }) var stm32_esp8266_obj = {}; var studentNo = "2020070230114";//替换你的学号 const subcribe_topic = `/ota/device/inform/iqfzjbFKlyh/js_node_one`; const publish_topic = `/ota/device/upgrade/iqfzjbFKlyh/js_node_one`; client.on('connect', () => {D:/users/deskttop/iot/sy4/iot_cloudesp8266_mqtt_expresss console.log('MQTT Connected') client.subscribe([subcribe_topic], () => { console.log(`Subscribe to topic '${subcribe_topic}'`) }); setInterval(()=>{ var chushuiliang1=Math.floor(Math.random() * 20)+1; var chushuiliang2=Math.floor(Math.random() * 40)+1; var jinshuiliang=chushuiliang1+chushuiliang2+Math.floor(Math.random() * 10)+1; var zhuodu2 = Math.floor(Math.random() * 20)+1; var zhuodu3 = Math.floor(Math.random() * 20)+1; var zhuodu1 = zhuodu2+zhuodu3+Math.floor(Math.random() * 5)+1; var publish_obj={ error:0, wendu1:Math.floor(Math.random() * 40), wendu2:Math.floor(Math.random() * 40), yulv1:Math.random().toFixed(4), yulv2:Math.random().toFixed(4), yewei:Math.random().toFixed(4), ph1:Math.floor(Math.random() * 13), ph2:Math.floor(Math.random() * 13), shui:[jinshuiliang,chushuiliang1,chushuiliang2], zhuodu:[zhuodu1,zhuodu2,zhuodu3] } client.publish(publish_topic, JSON.stringify(publish_obj), { qos: 0, retain: false }, (error) => { if (error) { console.error(error) } }) },5000); }) client.on('message', (topic, payload) => { console.log('Received Message:', topic, payload.toString()); stm32_esp8266_obj = JSON.parse(payload); // console.log(stm32_esp8266_obj); })
06-08

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值