搭建express服务器

express是一个基于Node.js的极简的web应用程序开发框架。

首先为应用程序创建一个package.js文件

npm init -y

在项目目录添加index.js文件

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!'))

启动

node index.js

然后在浏览器中访问http://localhost:3000/就可以看到返回的'Hello wORLD!'文本了。

路由指定了如何对对应的URI请求进行响应,例如下面的各种请求

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内置中间件函数。

express.static(root, [options])

下面代码对外开放了public目录下的文件

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

然后就可以直接访问public目录下面的文件了,Express 在静态目录查找文件,因此,存放静态文件的目录名不会出现在 URL 中。

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访问了

猜你喜欢

转载自www.cnblogs.com/ssw-men/p/11490610.html