一、今日学习内容: 1、使用Express构造Web服务器 # 下载 express 模块 npm i express //1. 加载 express 模块 const express = require('express'); //2. 创建express(Web) 服务器 const app = express(); //3. 开启服务器 app.listen(3000, () => { console.log('express-server is running...'); }) //4. 监听浏览器请求并进行处理 //get(): 用来接收get请求 app.get('/index', (req, res) => { res.end('index-page'); }) app.get('/login', (req, res) => { //send方法是express封装的方法 res.send('登录页'); }) // * : 通配符,代表任意地址 app.get('*', (req, res) => { res.send('404 not found'); }) 2、Express中使用art-template 在Express框架中不能直接使用art-template模板引擎,使用Express-art-template中间件来加载。 使用步骤: 1) 下载/安装 npm i art-template express-art-template 2) 在服务器文件中加载 express-art-template const template = require('express-art-template'); 3) 配置express调用的模板引擎 //设置模板引擎类型 //参数1: 模板文件的后缀,此处可以随意定义。 定义成什么,模板文件后缀就是什么。一般 使用html即可 //参数2: 模板引擎对象 app.engine('html', template); 4) 渲染页面 将模板页和数据组装到一起 (渲染数据) ① 数据 : js对象 ② 模板页: 输出数据的方法和之前一样 //render方法是express提供好的方法,不管我们使用什么模板引擎都能使用该方法渲染页面 //参数1: 模板文件路径 //参数2: 要渲染到页面的json数据 res.render(filepath, js); 3、 post方式提交数据 express 中接收 post方式提交的数据需要使用 body-parser 模块 body-parser 是一个第三方模块,现在已经被 express 集成 使用 body-parser 来接收表单数据时,表单数据会直接挂载到 req对象的 body属性下,以对象形式保存 使用步骤: 1)加载 body-parser 模块 const bodyParser = require('body-parser'); 2)注册为中间件app.use(bodyParser.urlencoded({extended:false})) // {extended:false} 代表使用node的 querystring 模块来解析表单数据 3)使用req对象的body属性来获取表单数据 console.log(req.body) 4、数据库mysql的增删改查 二、今日问题:node模块使用上仍旧有点问题,对于每个模块实际应用不够熟悉 三、解决方案:无
|