NODEJS Express 4 API 中文手册.docx
《NODEJS Express 4 API 中文手册.docx》由会员分享,可在线阅读,更多相关《NODEJS Express 4 API 中文手册.docx(62页珍藏版)》请在冰豆网上搜索。
NODEJSExpress4API中文手册
Express4.xAPI中文手册
express()
创建一个Express应用。
express() 是一个由 express 模块导出的入口(top-level)函数。
varexpress=require('express');
varapp=express();
内置方法
express.static(root,[options])
express.static 是Express内置的唯一一个中间件。
是基于 serve-static 开发的,负责托管Express应用内的静态资源。
root 参数指的是静态资源文件所在的根目录。
options 对象是可选的,支持以下属性:
属性
描述
类型
默认值
dotfiles
Optionforservingdotfiles.Possiblevaluesare“allow”,“deny”,and“ignore”
String
“ignore”
etag
Enableordisableetaggeneration
Boolean
true
extensions
Setsfileextensionfallbacks.
Boolean
false
index
Sendsdirectoryindexfile.Set false todisabledirectoryindexing.
Mixed
“index.html”
lastModified
Setthe Last-Modified headertothelastmodifieddateofthefileontheOS.Possiblevaluesare trueor false.
Boolean
true
maxAge
Setthemax-agepropertyoftheCache-Controlheaderinmillisecondsorastringin msformat
Number
0
redirect
Redirecttotrailing“/”whenthepathnameisadirectory.
Boolean
true
setHeaders
FunctionforsettingHTTPheaderstoservewiththefile.
Function
关于此中间件的细节,请参考 通过Express托管静态资源文件。
Application
The app objectconventionallydenotestheExpressapplication.Createitbycallingthetop-level express() functionexportedbytheExpressmodule:
varexpress=require('express');
varapp=express();
app.get('/',function(req,res){
res.send('helloworld');
});
app.listen(3000);
The app objecthasmethodsfor
∙RoutingHTTPrequests;seeforexample, app.METHOD and app.param.
∙Configuringmiddleware;see app.route.
∙RenderingHTMLviews;see app.render.
∙Registeringatemplateengine;see app.engine.
Italsohassettings(properties)thataffecthowtheapplicationbehaves;formoreinformation,see Applicationsettings.
Properties
app.locals
The app.locals objectisaJavaScriptobject,anditspropertiesarelocalvariableswithintheapplication.
app.locals.title
//=>'MyApp'
app.locals.email
//=>'me@'
Onceset,thevalueof app.locals propertiespersistthroughoutthelifeoftheapplication,incontrastwith res.locals propertiesthatarevalidonlyforthelifetimeoftherequest.
Youcanaccesslocalvariablesintemplatesrenderedwithintheapplication.Thisisusefulforprovidinghelperfunctionstotemplates,aswellasapp-leveldata.Note,however,thatyoucannotaccesslocalvariablesinmiddleware.
app.locals.title='MyApp';
app.locals.strftime=require('strftime');
app.locals.email='me@';
app.mountpath
The app.mountpath propertyisthepathpattern(s)onwhichasubappwasmounted.
Asubappisaninstanceof express whichmaybeusedforhandlingtherequesttoaroute.
varexpress=require('express');
varapp=express();//themainapp
varadmin=express();//thesubapp
admin.get('/',function(req,res){
console.log(admin.mountpath);///admin
res.send('AdminHomepage');
})
app.use('/admin',admin);//mountthesubapp
Itissimilartothe baseUrl propertyofthe req object,except req.baseUrl returnsthematchedURLpath,insteadofthematchedpattern(s).
Ifasub-appismountedonmultiplepathpatterns, app.mountpath returnsthelistofpatternsitismountedon,asshowninthefollowingexample.
varadmin=express();
admin.get('/',function(req,res){
console.log(admin.mountpath);//['/adm*n','/manager']
res.send('AdminHomepage');
})
varsecret=express();
secret.get('/',function(req,res){
console.log(secret.mountpath);///secr*t
res.send('AdminSecret');
});
admin.use('/secr*t',secret);//loadthe'secret'routeron'/secr*t',onthe'admin'subapp
app.use(['/adm*n','/manager'],admin);//loadthe'admin'routeron'/adm*n'and'/manager',ontheparentapp
Events
app.on('mount',callback(parent))
The mount eventisfiredonasub-app,whenitismountedonaparentapp.Theparentappispassedtothecallbackfunction.
varadmin=express();
admin.on('mount',function(parent){
console.log('AdminMounted');
console.log(parent);//referstotheparentapp
});
admin.get('/',function(req,res){
res.send('AdminHomepage');
});
app.use('/admin',admin);
Methods
app.all(path,callback[,callback...])
Thismethodislikethestandard app.METHOD() methods,exceptitmatchesallHTTPverbs.
It’susefulformapping“global”logicforspecificpathprefixesorarbitrarymatches.Forexample,ifyouputthefollowingatthetopofallotherroutedefinitions,itrequiresthatallroutesfromthatpointonrequireauthentication,andautomaticallyloadauser.Keepinmindthatthesecallbacksdonothavetoactasend-points:
loadUser canperformatask,thencall next() tocontinuematchingsubsequentroutes.
app.all('*',requireAuthentication,loadUser);
Ortheequivalent:
app.all('*',requireAuthentication)
app.all('*',loadUser);
Anotherexampleiswhite-listed“global”functionality.Theexampleismuchlikebefore,howeveritonlyrestrictspathsthatstartwith“/api”:
app.all('/api/*',requireAuthentication);
app.delete(path,callback[,callback...])
RoutesHTTPDELETErequeststothespecifiedpathwiththespecifiedcallbackfunctions.Formoreinformation,seethe routingguide.
Youcanprovidemultiplecallbackfunctionsthatbehavejustlikemiddleware,exceptthesecallbackscaninvoke next('route') tobypasstheremainingroutecallback(s).Youcanusethismechanismtoimposepre-conditionsonaroute,thenpasscontroltosubsequentroutesifthere’snoreasontoproceedwiththecurrentroute.
app.delete('/',function(req,res){
res.send('DELETErequesttohomepage');
});
app.disable(name)
SetstheBooleansetting name to false,where name isoneofthepropertiesfromthe appsettingstable.Calling app.set('foo',false) foraBooleanpropertyisthesameascalling app.disable('foo').
Forexample:
app.disable('trustproxy');
app.get('trustproxy');
//=>false
app.disabled(name)
Returns true iftheBooleansetting name isdisabled(false),where name isoneofthepropertiesfromthe appsettingstable.
app.disabled('trustproxy');
//=>true
app.enable('trustproxy');
app.disabled('trustproxy');
//=>false
app.enable(name)
SetstheBooleansetting name to true,where name isoneofthepropertiesfromthe appsettingstable.Calling app.set('foo',true) foraBooleanpropertyisthesameascalling app.enable('foo').
app.enable('trustproxy');
app.get('trustproxy');
//=>true
app.enabled(name)
Returns true ifthesetting name isenabled(true),where name isoneofthepropertiesfromthe appsettingstable.
app.enabled('trustproxy');
//=>false
app.enable('trustproxy');
app.enabled('trustproxy');
//=>true
app.engine(ext,callback)
Registersthegiventemplateengine callback as ext.
Bydefault,Expresswill require() theenginebasedonthefileextension.Forexample,ifyoutrytorendera“foo.jade”file,Expressinvokesthefollowinginternally,andcachesthe require() onsubsequentcallstoincreaseperformance.
app.engine('jade',require('jade').__express);
Usethismethodforenginesthatdonotprovide .__express outofthebox,orifyouwishto“map”adifferentextensiontothetemplateengine.
Forexample,tomaptheEJStemplateengineto“.html”files:
app.engine('html',require('ejs').renderFile);
Inthiscase,EJSprovidesa .renderFile() methodwiththesamesignaturethatExpressexpects:
(path,options,callback),thoughnotethatitaliasesthismethodas ejs.__express internallysoifyou’reusing“.ejs”extensionsyoudon’tneedtodoanything.
Sometemplateenginesdonotfollowthisconvention.The consolidate.js librarymapsNodetemplateenginestofollowthisconvention,sotheyworkseemlesslywithExpress.
varengines=require('consolidate');
app.engine('haml',engines.haml);
app.engine('html',engines.hogan);
app.get(name)
Returnsthevalueof name appsetting,where name isoneofstringsinthe appsettingstable.Forexample:
app.get('title');
//=>undefined
app.set('title','MySite');
app.get('title');
//=>"MySite"
app.get(path,callback[,callback...])
RoutesHTTPGETrequeststothespecifiedpathwiththespecifiedcallbackfunctions.Formoreinformation,seethe routingguide.
Youcanprovidemultiplecallbackfunctionsthatbehavejustlikemiddleware,exceptthesecallbackscaninvoke next('route') tobypasstheremainingroutecallback(s).Youcanusethismechanismtoimposepre-conditionsonaroute,thenpasscontroltosubsequentroutesifthere’snoreasontoproceedwiththecurrentroute.
app.get('/',function(req,res){
res.send('GETrequesttohomepage');
});
app.listen(port,[hostname],[backlog],[callback])
Bindsandlistensforconnectionsonthespecifiedhostandport.ThismethodisidenticaltoNode’s http.Server.listen().
varexpress=require('express');
varapp=express();
app.listen(3000);
The app returnedby express() isinfactaJavaScript Function,designedtobepassedtoNode’sHTTPserversasacallbacktohandlerequests.ThismakesiteasytoprovidebothHTTPandHTTPSversionsofyourappwiththesamecodebase,astheappdoesnotinheritfromthese(itissimplyacallback):
varexpress=require('express');
varhttps=require('https');
varhttp=require('http');
varapp=express();
http.createServer(app).listen(80);
https.createServer(options,app).listen(443);
The app.listen() methodisaconveniencemethodforthefollowing(forHTTPonly):
app.listen=function(){
varserver=http.createServer(this);
returnserver.listen.apply(server,arguments);
};
app.METHOD(path,callback[,callback...])
RoutesanHTTPrequest,whereMETHODistheHTTPmethodoftherequest,suchasGET,PUT,POST,andsoon,inlowercase.Thus,theactualmethodsare app.get(), app.post(), app.put(),andsoon.Seeb