首页 > 代码库 > 新手的 express4.0 笔记 api
新手的 express4.0 笔记 api
app.set(name, value)
settings
The following settings will alter how Express behaves:
express内置的参数
env
Environment mode, defaults toprocess.env.NODE_ENV
(NODE_ENV environment variable) or "development"trust proxy
Enables reverse proxy support, disabled by defaultsubdomain offset
The number of dot-separated parts of the host to remove to access subdomain, two by defaultjsonp callback name
Changes the default callback name of?callback=
json replacer
JSON replacer callback, null by defaultcase sensitive routing
Enable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the samestrict routing
Enable strict routing, by default "/foo" and "/foo/" are treated the same by the routerview cache
Enables view template compilation caching, enabled in production by defaultview engine
The default engine extension to use when omittedviews
The view directory path, defaulting to "process.cwd() + ‘/views‘"x-powered-by
Enables theX-Powered-By: Express
HTTP header, enabled by default
也可以自定义参数
Assigns setting name
to value
.
app.set(‘title‘, ‘My Site‘);app.get(‘title‘);// => "My Site"
app.get(name)
Get setting name
value.
app.get(‘title‘);// => undefinedapp.set(‘title‘, ‘My Site‘);app.get(‘title‘);// => "My Site"
app.use([path], function)
Use the given middleware function
(with optional mount path
, defaulting to "/").
var express = require(‘express‘);var app = express();// simple loggerapp.use(function(req, res, next){ console.log(‘%s %s‘, req.method, req.url); next();});// respondapp.use(function(req, res, next){ res.send(‘Hello World‘);});app.listen(3000);
将指定的中间件挂在到路径上,默认的路径是"/"
The "mount" path is stripped and is not visible to the middleware function
. This feature is mainly to ensure that mounted middleware may operate without code changes, regardless of the "prefix" pathname.
Here‘s a concrete example. Take the typical use-case of serving files in ./public using the express.static()
middleware:
app.use(express.static(__dirname + ‘/public‘));
指定文件路径,相当于windows的环境设置
假设设置了以上的代码,就可以访问localhost:3000/photo.jpg 相当于直接访问
localhost:3000/public/photo.jpg
而这个访问的内部是隐藏起来的,你是无法知道真实的路径的 这样可以确保代码经过修改后无需关注前缀名称
下面是更加详尽的代码解释
var logger = require(‘morgan‘);app.use(logger());app.use(express.static(__dirname + ‘/public‘));app.use(function(req, res){ res.send(‘Hello‘);});
app.use(express.static(__dirname + ‘/public‘));app.use(logger());app.use(function(req, res){ res.send(‘Hello‘);});
测试访问http://localhost:3000/11.jpg
上面第一段使用中间件有显示路径 GET /11.jpg, 而第二段代码则没显示
app.use(express.static(__dirname + ‘/public‘));app.use(express.static(__dirname + ‘/files‘));app.use(express.static(__dirname + ‘/uploads‘));
/public会优先于其他几个
新手的 express4.0 笔记 api
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。