使用toolbox命令创建一个新项目:vapor new projectname
在main.swift文件中,我添加了中间件代码:
import Vapor
import HTTP
final class VersionMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response = try next.respond(to: request)
response.headers["Version"] = "API v1.0"
print("not printing")
return response
}
}
let drop = Droplet(availableMiddleware: [
"version": VersionMiddleware()
])
drop.get("hello") {
req in
return "Hello world"
}
drop.run()
但是当我运行它时,它会打印出#34; hello world"但API版本未添加到标头中。我正在用邮递员检查它。
答案 0 :(得分:2)
答案 1 :(得分:2)
Vapor1➙2迁移注意:"中间件"订购配置已从 Config / middleware.json 移至 Config / droplet.json 。
Vapor 2
在Vapor 2中,可以按如下方式创建,添加和配置中间件:
源/应用/中间件/ ExampleMiddleware.swift
final class ExampleMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
// if needed, process inbound `request` here.
// Swift.print(request.description)
// pass next inbound `request` to next middleware in processing chain
let response: Response = try next.respond(to: request)
// if needed, process outbound `response` here
// Swift.print(response.description)
// return `response` to chain back up any remaining middleware to client
return response
}
}
源/应用/设置/配置+ Setup.swift
extension Config {
public func setup() throws {
…
try setupMiddleware()
…
}
public func setupMiddleware() throws {
self.addConfigurable(
middleware: ExampleMiddleware(),
name: "example"
)
}
}
配置/ droplet.json
"middleware": [
…,
"example"
],
注意:中间件直接包含在Vapor 2中(例如"错误","会话","文件","日期",如果没有Config/droplet.json
设置步骤,"middleware"
addConfigurable(middleware, name)
将使用" cors")。