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 - 对开发人员很方便,但对于实时代码,您应该更加挑剔并验证任何给定的 Origins、Methods 和 Headers。
BedSheetMiddleware
应该贡献给MiddlewarePipeline
服务:
@Contribute { serviceType=MiddlewarePipeline# }
static Void contributeMiddleware(Configuration config) {
config.set("myApp.cors", config.autobuild(CorsMiddleware#)).before("afBedSheet.routes")
}
请注意,它在 BedSheet 路由之前CorsMiddleware
插入到管道中,以确保它被执行。