新手的 express4.0 笔记 api

app.set(name, value)

settings

The following settings will alter how Express behaves:

 express内置的参数

    • env Environment mode, defaults to process.env.NODE_ENV (NODE_ENV environment variable) or "development"
    • trust proxy Enables reverse proxy support, disabled by default
    • subdomain offsetThe number of dot-separated parts of the host to remove to access subdomain, two by default
    • jsonp callback name Changes the default callback name of ?callback=
    • json replacer JSON replacer callback, null by default
    • case sensitive routing Enable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the same
    • strict routing Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router
    • view cache Enables view template compilation caching, enabled in production by default
    • view engine The default engine extension to use when omitted
    • views The view directory path, defaulting to "process.cwd() + ‘/views‘"
    • x-powered-by Enables the X-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‘);
// => undefined

app.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 logger
app.use(function(req, res, next){
  console.log(%s %s, req.method, req.url);
  next();
});

// respond
app.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

上一篇:剑指 Offer 50. 第一个只出现一次的字符(python3编写)


下一篇:剑指 Offer 63. 股票的最大利润