概要
在middleware.json中配置middleware。下面是使用Application generator创建的默认版本:
{ "initial:before": { "loopback#favicon": {} }, "initial": { "compression": {} "cors": { "params": { "origin": true, "credentials": true, "maxAge": 86400 } }, "session": { }, "auth": { }, "parse": { }, "routes": { }, "files": { }, "final": { "loopback#urlNotFound": {} }, "final:after": { "loopback#errorhandler": {} } }
Phases
middleware.json中的每个顶层属性都下面的一个middleware phases:
initial
- The first point at which middleware can runsession
- 准备session对象auth
- 处理验证 权限parse
- 解析请求主体routes
- HTTP routes implementing your application logic. Middleware registered via the Express APIapp.use
,app.route
,app.get
(and other HTTP verbs) runs at the beginning of this phase. Use this phase also for sub-apps likeloopback/server/middleware/rest
orloopback-explorer
.files
- 处理静态资源(请求是在这命中文件系统的)final
- 处理错误和对非法URL的请求
每个phase都有"before"和"after"两个子phase。例子,对于"initial" phase, middleware按下面的顺序执行:
initial:before
initial
initial:after
Middleware within a single subphase executes in the order in which it is registered. However, you should not rely on such order. Always explicitly order the middleware using appropriate phases when order matters.
通常,每个phase有下面的语法:
middlewarePath : {
[ enabled: [true | false] ]
[, name: nameString ]
[, params : paramSpec ]
[, methods: methodSpec ]
[ paths : routeSpec ]
}
}
- phase 是上面列出的phase (如initial, session, auth, 等)或者是一个自定义的phase; 详见Adding a custom phase
- sub-phase (可选) 可以是before或者after
- name: (可选)middleware 名
- middlewarePath: middleware函数的路径
- paramSpec: middlewaer参数的值,通常是一个JSON对象
- methodSpec: 一个数组,包含middleware可以被触发的HTTP方法;例如
"methods" : ["GET", "POST"]。如果没有写,那么默认支持所有的HTTP方法
- routeSpec: 会触发middleware的REST endpoint(s)
更对信息,见Defining middleware.
CORS设置
在initial phase中通过配置cors.params
属性来设置跨域资源共享 (CORS)。更多信息,见cors。
属性 | 类型 | 描述 | 默认值 |
---|---|---|---|
cors.params.origin | Boolean | Configures the Access-Control-Allow-Origin CORS header. Expects a string (ex: "http://example.com/"). Set to
| true |
cors.params.credentials | Boolean | Configures the Access-Control-Allow-Credentials CORS header. Set to You can set other cors properties as well. For more information, see cors. | true |
cors.params.maxAge | Number | Configures the Access-Control-Allow-Max-Age CORS header. Set to an integer to pass the header, otherwise it is omitted. | 86400 |