wrap-cors不会返回访问控制标头。我相信这是因为我使用的异常处理程序可能会阻止中间件运行。我想知道如何仍然可以为此路由执行中间件并将cors标头附加到错误请求的响应中。
异常处理程序
(defn- bad-request-handler
"Handles bad requests."
[f]
(f
(ring/response {:status "bad request"})))
app
(def app
(api
{:exceptions {:handlers
{::ex/request-validation (bad-request-handler response/bad-request)}}}
(POST "/" [] :body [item {(schema/required-key :item) schema/Bool}]
:middleware [#(wrap-cors % :access-control-allow-origin [#".*"]
:access-control-allow-methods [:post])]
:responses {200 {:description "ok"}
400 {:description "bad request"}} item)))
答案 0 :(得分:0)
我决定添加自己的标题,而不是使用r0man / ring-cors。
我可以通过从请求中获取Access-Control-Allow-Methods
的值来确定:request-method
的内容。
但是,这假设错误的请求处理程序将仅由有效路由调用。
(defn- append-cors
"Allow requests from all origins"
[methods]
{"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Methods" methods})
(defn- bad-request-handler
"Handles bad requests."
[f]
(fn [^Exception e data request]
(->
(f request)
(update-in [:headers] merge (->
(request :request-method)
(name)
(clojure.string/upper-case)
(append-cors)))
(assoc :body {:status "bad request"}))))
我仍然不太确定为什么只在允许请求时才添加cors标头。