本篇,我们介绍下nodejs中常用的web开发框架--Express。
Express 是一个简洁而灵活的 node.js Web应用框架, 提供一系列强大特性帮助你创建各种Web应用。Express 不对 node.js 已有的特性进行二次抽象,只是在它之上扩展了Web应用所需的功能。丰富的HTTP工具以及来自Connect框架的中间件随取随用,创建强健、友好的API变得快速又简单。
使用express之前 需要先安装express模块 ,进入项目根目录,执行 npm install express --save 即可。
express api, express搭建静态web站点,express搭建静态虚拟目录, express路由中间件 介绍
app.get(fn), app.post(fn),app.use(fn), express.static() 等.
//01_express.js
//介绍 express api, express搭建静态web站点,express搭建静态虚拟目录, express路由中间件
// npm install express --save 安装express模块
//Express 4.x API 中文手册 http://www.expressjs.com.cn/4x/api.html
var express=require('express');
var app=express();
//搭建静态web站点 浏览器访问 http://localhost:3000/a.html
//app.use(express.static("./static"));
//搭建虚拟web目录 浏览器访问 http://localhost:3000/static/a.html
app.use("/static",express.static("./static"));
app.get("/",function (req,res) {
res.send('ok');
});
//配置错误中间件 (500)
app.use(function (err,req,res,next) {
res.status(500).type("html").end('<h3 style="text-align: center">500 - server internal error</h3>');
});
//配置404 路由中间件 这个中间件应该配置在最后
app.use(function (req,res) {
res.status(404).type("html").end('<h3 style="text-align: center">404 - page not found</h3>');
});
app.listen(3000);