新建一个文件夹,添加package.json
123456789{"name": "hello-world","description": "hello world test app","version": "0.0.1","private": true,"dependencies": {"express": "4.x"}}npm install
安装依赖- 123456var express = require('express');var app = express();app.get('/', function (req, res) {res.send('Hello world!');});app.listen(3000);
以上代码相当于:
12345678var 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");
运行index.js
中间件
Express框架的核心是对http模块的再包装,相当于在http模块上加了一个中间层。
简单说,中间件(middleware)就是处理HTTP请求的函数。
特点:一个中间件处理完,再传递给下一个中间件。App实例在运行过程中,会调用一系列的中间件。
每个中间件可以从App实例,接收三个参数,依次为request对象(代表HTTP请求)、response对象(代表HTTP回应),next回调函数(代表下一个中间件)。每个中间件都可以对HTTP请求(request对象)进行加工,并且决定是否调用next方法,将request对象再传给下一个中间件。
next回调函数中如果包含参数,表示抛出了一个错误,不再执行后边的中间件。
use()
Express中注册中间件的方法,返回一个函数,顺序调用
|
|
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(会报错)