之前的使用 connect 创建服务器的方法:
require("connect").createServer()
现在报错:TypeError: connect.createServer is not a function
。
- 因为 connect 在更新之后就取消了这种创建服务的方法,connect 作为一个继承自 http 的中间件(Connect is an extensible HTTP server framework for node using "plugins" known as middleware),现在使用和创建服务的方法调整如下:
/**
* Created by yjw on 2017/12/23.
*/
var http = require("http");
var connect = require("connect");
var app = connect();
var time = require("./time.js");
//记录请求情况
//app.use(connect.logger("dev"));
//实现中间件
app.use(time({time:500}));
//实现快速响应
app.use(function(req,res,next){
if("/a"==req.url){
res.writeHead(200);
res.end("Fast!!!");
}else{
next();
}
});
//实现模拟的慢速响应
app.use(function(req,res,next){
if("/b"==req.url){
setTimeout(function(){
res.writeHead(200);
res.end("Slow!!!");
},1000);
}else{
next();
}
});
//create node.js http server and listen on port
http.createServer(app).listen(3011);
- time.js 为我实现的一个中间件,不再 po 出,这里主要说明 connect 更新之后如何创建服务。
其中 app.use(connect.logger("dev"));
报错:TypeError: connect.logger is not a function
:
- 原因是一些中间件和库都做了更新,目前被抛弃和与之对应的新库或者中间件总结如下:
1.body-parser - previous bodyParser
, json
, and urlencoded
. You may also be interested in:body,co-body,raw-body
2.compression - previously compress
3.connect-timeout - previously timeout
4.cookie-parser - previously cookieParser
5.cookie-session - previously cookieSession
6.csurf - previously csrf
7.errorhandler - previously error-handler
8.express-session - previously session
9.method-override - previously method-override
10.morgan - previously logger
11.response-time - previously response-time
12.serve-favicon - previously favicon
13.serve-index - previously directory
14.serve-static - previously static
15.vhost - previously vhost
`app.use(connect.logger("dev"));修改完用法如下:
var morgan = require("morgan");
//记录请求情况
app.use(morgan("dev"));
- 前提:使用 npm 安装 connect 和 morgan。