1、请求与响应
const express = require('express')var app = express();app.get('/', function(req, res) { res.end('hello')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
具体的API可以查看:
nodemon:一个可以监听文件修改,自动重启node服务的插件。
只需要全局安装,使用nodemon server
命令,会自动查找当前目录的server.js
2、路由参数(动态路由)
const express = require('express')var app = express();app.get('/profile/:id/user/:name', function (req, res) { console.log(req.params) //获取有所动态路由的id res.end(`id=${req.params.id}`)})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
路由可以使用正则表达式
3、查询字符串
const express = require('express')var app = express();app.get('/', function(req, res) { console.log(req.query) //通过req.query获取?a=1 res.end('hello')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
4、解析POST参数
解析post请求参数需要借助body-parse
中间件,安装这个中间件。
解析Form Data数据
这种方式的请求Content-Type: 'application/x-www-form-urlencoded'
这种是form表单提交过来的数据,用法./server.js
const path = require('path')const fs = require('fs')const express = require('express')const bodyParser = require('body-parser')var app = express();/**[解析form提交过来的数据] */app.use(bodyParser.urlencoded({ extended: false }))app.post('/login', function(req, res) { // [这里接收传递过来的参数] console.log( req.body ) res.send('ok')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
解析Request Paylod数据
这种请求方式的Content-Type: 'application/json;charset=UTF-8'
使用ajax或者fetch传递过来的json./server.js
const path = require('path')const fs = require('fs')const express = require('express')const bodyParser = require('body-parser')var app = express();/**[解析ajax或者fetch传递过来的json] */app.use(bodyParser.json())app.post('/login', function(req, res) { // [这里接收传递过来的参数] console.log( req.body ) res.send('ok')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
解析2种参数
const path = require('path')const fs = require('fs')const express = require('express')const bodyParser = require('body-parser')var app = express();const bodyAjax = bodyParser.json()const bodyForm = bodyParser.urlencoded({ extended: false })app.post('/login_form',bodyForm, function(req, res) { // [这里接收传递过来的参数] console.log( req.body , 'bodyForm') res.send('ok')})app.post('/login_ajax', bodyAjax, function(req, res) { // [这里接收传递过来的参数] console.log( req.body , 'bodyAjax') res.send('ok')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
5、上传文件
安装处理文件程序:multer
./index.html
Document hello world
./server.js
const path = require('path')const fs = require('fs')const express = require('express')const bodyParser = require('body-parser')var multer = require('multer') //[处理上传过来的文件]// 创建目录function createDir(dirPath) { try { fs.accessSync(dirPath) } catch(e) { fs.mkdirSync(dirPath) }}//要存储的目录const uploadDir = __dirname + '/uploads'createDir(uploadDir)//存储文件配置var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, uploadDir) }, filename: function (req, file, cb) { //拼接成带时间戳的文件名(防止重名导致覆盖) var filename = file.originalname.replace(/\.([a-zA-Z]*)$/, `-${Date.now()}.`) cb(null, filename + RegExp.$1 ) }})var upload = multer({ storage: storage })var app = express();/**[对index.html做映射] */app.get('/', function(req, res) { fs.createReadStream(__dirname + './index.html', 'utf8').pipe(res)})// upload.single('logo') 中的这个字段一定要和上传上来的字段匹配app.post('/upload', upload.single('logo'), function(req, res, next) { console.log( req.file.originalname ) res.send('上传成功')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
6、使用ejs模板引擎
使用ejs作为模板引擎,渲染变量、列表、包含子模块。
./server.js
const express = require('express')const app = express();/**[设置模板引擎的根目录] */app.set('views', './views')/**[使用ejs模板引擎] */app.set('view engine', 'ejs')/**[对index.ejs做映射] */app.get('/', function(req, res) { const data = { age: 12, name: 'david', list: [ { title: '水果', price: 19 }, { title: '水果', price: 19 }, { title: '水果', price: 19 } ] } res.render('index.ejs', { data })})app.get('/about', function(req, res) { res.render('about')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
./views/index.ejs
使用ejs模板引擎 <%- include('header'); %>hello world
姓名:<%= data.name %>
年龄:<%= data.age %>
购物车:<%= data.age %>
- <% data.list.forEach(function (item) { %>
- 水果名:<%= item.title %>,价格:<%= item.price %> <% }) %>
./views/header.ejs
./views/about.ejs
Document <%- include('header') %>about.ejs
7、中间件
处理request、response插件称为中间件
./server.js
const express = require('express')const app = express();//中间件app.use(function(req, res, next) { console.log(111) next()})//中间件app.use(function(req, res, next) { next()})app.get('/', function(req, res, next) { res.send('hello
')})app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
输出:111 222
8、使用路由中间件
./server.js
const express = require('express')const app = express();const index = require('./routes/index')const users = require('./routes/users')app.use('/', index)app.use('/users', users)app.listen(3000)console.log( 'server listening to 3000, http://localhost:3000' )
新建文件夹./routes
,./routes/index.js
var express = require('express')var router = express.Router();router.get('/', function(req, res, next) { res.send('home')})module.exports = router
./routes/users.js
var express = require('express')var router = express.Router();router.get('/', function(req, res, next) { res.send('users')})module.exports = router
这样配置,既可以完成将路由当做中间件。
9、项目实践
需求
添加事项、删除事项、展示事项列表;
备注
线上MongoDB网址:mLab
使用Mongolass操纵Mongoose数据库