Express

Table of Contents

1. Express 简介

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

参考:http://expressjs.com/

2. 第一个 Express 工程

下面是使用 Express 创建 web 工程的基本步骤。

第一步,创建工程目录。

$ mkdir myapp
$ cd myapp

第二步,安装 express 依赖。
创建下面 package.json 文件:

$ cat package.json
{
  "name": "myapp",
  "version": "0.1.0",
  "dependencies": {
    "express": "~4.14.1"
  }
}

执行命令 npm install 下载安装依赖库 express。

第三步,创建你的应用程序。
下面是一个简单的应用程序(假设文件名为 app.js)。

const express = require('express')
const app = express()

app.get('/user1', function (req, res) {
  res.send('Hello user1!\n')
})
app.post('/user1', function (req, res) {
  res.send('Got a POST request, user1\n')
})

app.get('/user2', function (req, res) {
  res.send('Hello user2!\n')
})
app.post('/user2', function (req, res) {
  res.send('Got a POST request, user2\n')
})

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

const http = require('http')
const server = http.createServer(app)
server.listen(8000)
console.log("Server is listening on port 8000")

第四步,启动 server,并测试。

$ node app.js
Server is listening on port 8000

测试如下:

$ curl localhost:8000/user1
Hello user1!
$ curl localhost:8000/user2
Hello user2!
$ curl -X POST localhost:8000/user1
Got a POST request, user1
$ curl -X POST localhost:8000/user2
Got a POST request, user2

2.1. 返回静态文件

要让 Expess 返回静态文件(如 html, css, etc),配置 app.use(express.static('public')) 即可(其中 pulibc 是静态文件所在目录)。

假设工程 public 子目录中有文件 index.html,内容为:

<p>Welcome</p>

app.js 为:

const express = require('express')
const app = express()

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

const http = require('http')
const server = http.createServer(app)
server.listen(8000)
console.log("Server is listening on port 8000")

node app.js 启动应用后,测试如下:

$ curl localhost:8000/index.html
<p>Welcome</p>

Author: cig01

Created: <2017-07-05 Wed>

Last updated: <2017-11-10 Fri>

Creator: Emacs 27.1 (Org mode 9.4)