前面已经开发出简单的登录,后面将会进入到进阶阶段,打算开发博客,商城等等若干系统
这篇是补充一些知识
1:关于html的后缀,大家知道,若干是ejs模块那么后缀天生的就是.ejs,那么是否可变呢,我们知道java中是可以的,在配置文件中配置一下视图的后缀就可以了,这样代码会自动识别,我想用啥后缀就用啥后缀,是不是很任性呢?当然我们的node也是可以滴
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
其中第一句是让ejs能够识别后缀为’.html’的文件,app.engine 相当于 express2 中的 app.register 。
第二句是使在调用render函数时能自动为我们加上’.html’ 后缀。如果没有第二句,我们就得把res.render(‘users’)写成res.render(‘users.html’),否则会报错。
这样我们就可以让我们的html文件的后缀是.html哦
2:中间件
中间件是什么,学过java的人可能听过拦截器,中间件我感觉就跟这个雷同:间件(middleware)就是处理HTTP请求的函数,用来完成各种特定的任务,比如检查用户是否登录、分析数据、以及其他在需要最终将数据发送给用户之前完成的任务。 它最大的特点就是,一个中间件处理完,可以把相应数据再传递给下一个中间件。
一个不进行任何操作,只传递request对象的中间件,大致是这样的
function Middleware(request, response, next) {
next();
}
如果有参数
function Middleware(request, response, next) {
next('出错了!');
}
app.all()函数可以匹配所有的HTTP动词,也就是说它可以过滤所有路径的请求,如果使用all函数定义中间件,那么就相当于所有请求都必须先通过此该中间件。
举例,下面的例子中all函数就是给所有请求设置响应头
var express = require("express");
var app = express();
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); //设置响应头属性值
next();
});
app.get("/", function(request, response) {
response.end("欢迎来到首页!");
});
app.get("/about", function(request, response) {
response.end("欢迎来到about页面!");
});
app.get("*", function(request, response) {
response.end("404 - 未找到!");
});
app.listen(80);
上篇文章中app.js中用了好多use(),也注释了这是一种调用中间件方法
格式:app.use([path], function(request, response, next){});
任何连续调用两个中间件
var express = require('express');
var app = express();
app.use(function(request, response, next){
console.log("method:"+request.method+" ==== "+"url:"+request.url);
next();
});
app.use(function(request, response){
response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
response.end('示例:连续调用两个中间件');
});
app.listen(80);
当然中间件还有别的用法,比如根据不同的请求地址,返回不同的内容
var express = require("express");
var app = express();
app.use(function(request, response, next) {
if(request.url == "/") {
response.send("Welcome to the homepage!");
}else {
next();
}
});
app.use(function(request, response, next) {
if(request.url == "/about") {
response.send("Welcome to the about page!");
}else {
next();
}
});
app.use(function(request, response) {
response.send("404 error!");
});
app.listen(80);
3:日志管理
nodejs日志有很多方法,还没研究透彻,后面打算写小项目的时候穿插进去。敬请期待。。。