1. 新建一个文件夹,添加package.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    {
    "name": "hello-world",
    "description": "hello world test app",
    "version": "0.0.1",
    "private": true,
    "dependencies": {
    "express": "4.x"
    }
    }
  2. npm install 安装依赖

  3. 1
    2
    3
    4
    5
    6
    var express = require('express');
    var app = express();
    app.get('/', function (req, res) {
    res.send('Hello world!');
    });
    app.listen(3000);
    1. 以上代码相当于:

      1
      2
      3
      4
      5
      6
      7
      8
      var http = require("http");
      var app = http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.end("Hello world!");
      });
      app.listen(3000, "localhost");

    2. 运行index.js

中间件

Express框架的核心是对http模块的再包装,相当于在http模块上加了一个中间层。

简单说,中间件(middleware)就是处理HTTP请求的函数。

特点:一个中间件处理完,再传递给下一个中间件。App实例在运行过程中,会调用一系列的中间件。

每个中间件可以从App实例,接收三个参数,依次为request对象(代表HTTP请求)、response对象(代表HTTP回应),next回调函数(代表下一个中间件)。每个中间件都可以对HTTP请求(request对象)进行加工,并且决定是否调用next方法,将request对象再传给下一个中间件。

next回调函数中如果包含参数,表示抛出了一个错误,不再执行后边的中间件。

use()

Express中注册中间件的方法,返回一个函数,顺序调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
if (request.url == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
} else {
next();
}
});
app.use(function(request, response, next) {
if (request.url == "/about") {
response.writeHead(200, { "Content-Type": "text/plain" });
} else {
next();
}
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});

app.use(path,callback)中的callback既可以是router对象又可以是函数

app.get(path,callback)中的callback只能是函数

app.use(“/“,function(){}) //请求的是“/”时,执行第一个中间件 为啥~~~~~~

app.use(“/home”,function(){}) //执行对应的中间件

Q:res.send / res.end()

如果服务器端没有数据返回到客户端 那么就可以用 res.end

但是 如果 服务器端有数据返回到客户端 这个时候必须用res.send ,不能用 res.end(会报错)