express是一个基于Node.js的极简的web应用程序开发框架。css
首先为应用程序建立一个package.js文件html
npm init -y
在项目目录添加index.js文件node
const express = require('express') const app = express() app.get('/', (req, res) => res.send('Hello World!')) app.listen(3000, () => console.log('Example app listening on port 3000!'))
启动web
node index.js
而后在浏览器中访问http://localhost:3000/就能够看到返回的'Hello wORLD!'文本了。express
路由指定了如何对对应的URI请求进行响应,例以下面的各类请求npm
app.get('/', function (req, res) { res.send('Hello World!') }) app.post('/', function (req, res) { res.send('Got a POST request') }) app.put('/user', function (req, res) { res.send('Got a PUT request at /user') }) app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user') })
静态文件浏览器
为了提供CSS文件、图片、js文件之类的静态资源,能够使用express.static内置中间件函数。app
express.static(root, [options])
下面代码对外开放了public目录下的文件框架
app.use(express.static('public'))
而后就能够直接访问public目录下面的文件了,Express 在静态目录查找文件,所以,存放静态文件的目录名不会出如今 URL 中。dom
http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html
能够添加多个静态资源目录
app.use(express.static('public'))
app.use(express.static('files'))
能够提供一个虚拟的访问路径,路劲真实并不存在,但访问时须要加上。
app.use('/static', express.static('public'))
访问
http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
也能够提供一个绝对路径
app.use('/static', express.static(path.join(__dirname, 'public')))
除了get、post等方法设置路由外,还能够使用express.route()方法对同一个路径建立一个链式的路由回调
app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') })
express.Router
使用express.Router()能够建立一个模块化的、可装载的router处理函数。router能够做为middleware使用use加载,下面birds.js文件是一个Router模块。
var express = require('express') var router = express.Router() // middleware that is specific to this router router.use(function timeLog (req, res, next) { console.log('Time: ', Date.now()) next() }) // define the home page route router.get('/', function (req, res) { res.send('Birds home page') }) // define the about route router.get('/about', function (req, res) { res.send('About birds') }) module.exports = router
做为中间件使用router模块
var birds = require('./birds') // ... app.use('/birds', birds)
而后就能够使用/birds
and /birds/about访问了