Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
windowsjavascript
LTS
版本,下载安装包,Current
版本是开发版,不要下载,如图ubuntucss
运行如下命令html
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - sudo apt-get install -y nodejs
mac前端
安装完成后,运行以下命令检查是否安装成功,(以上方法安装node都会带上对应的npm,因此也须要检查一下npm是否安装成功。)java
node -v // 检查node版本 npm -v // 检查npm版本
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
npm install express -g // 全局安装express npm install express-generator -g // 全局安装express脚手架,安装以后可使用express命令 express --version // 检查express版本
mkdir app cd app /** * 生成项目文件 * express 默认使用ajs模板,加上 -e 指定更友好的ejs模板 */ express -e npm intall // 安装依赖 npm start // 启动项目
而后浏览器访问localhost:3000
,最简单的服务器就ok了。node
如何修改程序启动的默认3000
端口
Express 的启动目录是<project>/bin/www
,里面有一行代码:web
var port = normalizePort(process.env.PORT || '3000');
不难看出程序先去取process.env.PORT
(环境变量PORT)的值,没有就默认为3000
因此若是想改变端口,能够直接把3000
改为想要的端口号或者修改环境变量PORT的值,操做以下:
在启动程序以前,执行express
// ubuntu IOS export PORT=4000; // windows set PORT=4000;
而后执行npm start
,端口就被设置成了4000.npm
如何修改运行环境
Express默认的运行环境是development
,运行环境能够经过process.env.NODE_ENV
来获取,将系统环境设置为production
,代码以下:json
// ubuntu IOS export NODE_ENV=production // wondows set NODE_ENV=production
如何添加接口
在app.js
中,app.use('/', routes);
前面新增
app.get('/status', function (req, res) { res.send({status: 'ok'}); })
启动服务器,访问localhost:3000/status
,获得数据{status: 'ok'}
;
具体分析一下:app.get()
, get
是app对象的一个方法,负责处理get方法,改为post
,则只处理post
请求,不会处理别的请求,其他像put
,delete
相似。若写成use
,则会处理此路由任何方法的请求。/status
, 指定须要处理的路由
回调函数,即请求此路由的处理函数,它能够接收两个参数,三个参数,四个参数。一旦参数为四个就被express认定是错误处理函数
// app.js 里这就是个错误处理函数,用来处理全部路由上面抛出的错误,通常写在最后 app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); });
req
Express 封装的http request对象,包含headers
,query
,params
等自带属性。用来获取某次http请求的各项数据。
res
Express 封装的http reponse对象,包含send
,json
,jsonp
等方法。
next
若是执行next
,在执行完此处理函数以后,会继续向后找下一个处理函数,
app.get('/test-next', function(req, res, next) { console.log('first handler fn'); next(); }); app.get('/test-next', function(req, res, next) { res.send({status: 'second handler fn'}); });
浏览器访问localhoat:3000/test-next
,会获得{status: 'second handler fn'}
,
处理路由/test-next
,第一个回调函数,执行到next()
时,继续找下一个能处理/test-next
的回调.
什么是中间件
中间件(middlewear)是Express中的一个重要概念,Express使用中间件完成对请求体的改造,或者执行一些中间操做。归根结底,中间件就是一个函数,知足两个条件,
req
,res
,next
三个参数,最后执行next
函数,将处理权移交出去
写一个打印请求的中间件:
// 定义中间件,打印请求的方法和url function logRequest(req, res, next) { console.log(req.method, method.url); next(); } // 使用中间件 app.use(logRequest);
Express 如何处理路由
对于一个请求,Express处理通过一下流程
next()
则再也不往下执行,若是执行了next()
,会继续向下匹配。404
处理中间件,这个中间件会抛出一个错误,交由错误处理中间件处理。理解静态资源处理中间件app.use(express.static(path.join(__dirname, 'public')));
,express.static(PATH)
会将指定的目录下的全部资源做为静态资源。客户端能够输入指定资源的路径访问此资源。其实能够理解为将静态资源的路径,做为路由注册到了app
上。
若是要将文件<project>/public/stylesheets/style.css
,设置为静态资源,能够指定静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
也能够不设置静态文件,自定义路由
app.get('/stylesheets/style.css', function (req, res, next) { res.sendFile(path.join(__dirname, 'public/stylesheets/style.css')); })
两种方式访问http://localhost:3000/stylesheets/style.css
都能获得style.css
文件。
静态资源和用户自定义路由是等价的,因此,通常将静态资源处理中间件放在用户自定义中间件前面,避免路由冲突。
如何使用模板(默认使用ejs模板引擎)
// path 为.ejs模板的路径 // data 是给模板传入的值,必须是对象类型 res.render(<path>, [data]);
例如
app.js
app.get('/ejs', function(req, res, next) { res.render('index', { title: 'Express' }); });
index.ejs
<h1><%= title %></h1> <p>test ejs</p>
访问localhost:3000/ejs
便可看到结果。
ejs的经常使用语法以下
<% %> 在标签里能够写任意的 javascript 代码,能够把 javascript 代码拆开或者合在一块儿写,也能够与 html 标签一块儿写:
<% var a = 1 var b = 2 var c = a+b %> // var user = [1,2,3] <% for(let i=0; i<user.length; i++) { %> <p> html </p> <% } %>
<%= %> 输出转义后的内容
// ejs <p><%= '<lol>' %></p> // 转义后 <p><lol></p>
<%- %> 输出未转义的内容
// ejs <p><%- '<a href="http://www.baidu.com>baidu</a>' %></p> // 不转义的输出 <p><a href="http://www.baidu.com>baidu</a></p>
include 引入其余 ejs 文件,好比引用当前 ejs 文件同级目录下有一个名为 test.ejs 的文件,代码以下:
// exp1 <% var data = 1 %> <% include ./test %> // exp2 <%- include('test', {data:1}) %>