目录结构

nodejs简单使用ejs模板引擎,如何获取get、post请求传值_post请求

 

 在npm.com网站上搜索ejs的使用方法

下载ejs   

npm install ejs --save

 

app.js

const http = require('http');
const fs = require('fs');
const routes = require('./module/routes')
const url = require('url');
const ejs = require('ejs');

http.createServer(function (req, res) {
  // 注册路由
  routes.static(req,res,"static");

  let pathname = url.parse(req.url).pathname;

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

    let msg = "数据库里面获取的数据";
    let list = [
      {title:"新闻1"},
      {title:"新闻2"},
      {title:"新闻3"},
      {title:"新闻4"},
      {title:"新闻5"},
    ]
    ejs.renderFile("./views/login.ejs",{msg:msg,list:list},{},(err, data) => {
      res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
      res.end(data);
    })
  }else if(pathname === '/news'){
    // get请求
    // 获取请求类型
    console.log(req.method,"请求类型");
    var query = url.parse(req.url).query;
    console.log(query);
    res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
    res.end(query);
  }else if(pathname === '/form'){
    // 获取请求类型
    ejs.renderFile("./views/form.ejs",{},{},(err,data) => {
      res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
      res.end(data);
    })
  }else if(pathname === '/dologin'){
    // 获取post传值
    let postData = '';
    req.on('data',(chunk) => {
      postData += chunk;
    });
    req.on('end',() => {
      console.log(postData,"postData");
      res.end(postData)
    })
  }else{
    res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});
    res.end('<h1>这个页面不存在</h1>');
  }
  



  
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

views/login.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>
  <h2>ejs模板引擎</h2>
  <h3><%=msg%></h3>
  <br>
  <h2>列表渲染 "<%%><%%>"之间可以写javascript代码</h2>
  <ul>

    <%for(var i = 0;i < list.length;i++){%>
      <li><%=list[i].title%></li>
    <%}%>

  </ul>
  
</body>
</html>

views/form.ejs

用来发post请求

<!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>
  <form action="/dologin" method="post">
    用户名:<input type="text" name="username"/>
    <br>
    <br>
    密码:<input type="password" name="password"/>
    <br>
    <br>
    <input type="submit" value="提交">
  </form>
</body>
</html>