CORS必須手動設置,但如前所述,這並不困難。任何在請求處理程序方法中變得重複的東西通常都可能在某處丟失,而設置HTTP響應頭文件也不例外。這些可以通過BedSheet Middleware設置:
using afIoc
using afBedSheet
const class CorsMiddleware : Middleware {
@Inject private const HttpRequest req
@Inject private const HttpResponse res
@Inject private const ResponseProcessors processors
new make(|This|in) { in(this) }
override Void service(MiddlewarePipeline pipeline) {
// echo back in the response, whatever was sent in the request
res.headers["Access-Control-Allow-Origin"] = req.headers["Origin"]
res.headers["Access-Control-Allow-Methods"] = req.headers["Access-Control-Request-Method"]
res.headers["Access-Control-Allow-Headers"] = req.headers["Access-Control-Request-Headers"]
// deal with any pre-flight requests
if (req.httpMethod == "OPTIONS")
processors.processResponse(Text.fromPlain("OK"))
else
pipeline.service
}
}
注意,在所有請求上述將使CORS - 方便用於開發,而是活的代碼,你應該更加挑剔和驗證任何給定的起源,方法,和標題。
牀單Middleware
應促成MiddlewarePipeline
服務:
@Contribute { serviceType=MiddlewarePipeline# }
static Void contributeMiddleware(Configuration config) {
config.set("myApp.cors", config.autobuild(CorsMiddleware#)).before("afBedSheet.routes")
}
注意CorsMiddleware
插入管道前牀單路線,以確保其得到執行。