如何将 CORS 添加到 compojure-api 应用程序? [英] How do I add CORS to a compojure-api app?
问题描述
如何将 CORS 添加到此代码段?
How can I add CORS to this code snippet?
(def app
(api
{:swagger {:ui "/docs"
:spec "/swagger.json"}}
(GET "/route-a" [] "a")
(GET "/route-b" [] "b")
(GET "/route-c" [] "c")))
我想使用 https://github.com/r0man/ring-cors 并尝试过这个,但它似乎没有做任何事情.我想看到响应头包含 Access-Control-Allow-Origin 但它丢失了.
I would like to use https://github.com/r0man/ring-cors and have tried this, but it did not seem to do anything. I would like to see the response header contain Access-Control-Allow-Origin but it is missing.
(-> (api
{:swagger {:ui "/docs"
:spec "/swagger.json"}}
(GET "/route-a" [] "a")
(GET "/route-b" [] "b")
(GET "/route-c" [] "c"))
(wrap-cors :access-control-allow-origin #"http://localhost:81"
:access-control-allow-headers ["Origin" "X-Requested-With"
"Content-Type" "Accept"]
:access-control-allow-methods [:get :put :post :delete :options]))
推荐答案
仅当请求具有与指定正则表达式匹配的 Origin
标头时(当请求是在浏览器中使用 XMLHttpRequest
制作,自动添加 Origin 标头).
The CORS-specific response headers are returned only if the request has an Origin
header that matches the specified regex (when a request is made using XMLHttpRequest
in browser, the Origin header is added automatically).
如果您尝试:
curl -vH "Origin: http://localhost:81" localhost:3000/route-a
(假设您的 API 在端口 3000 上可用),您将看到添加了必要的响应标头.来自 http://localhost:81
的 AJAX 请求也应该有效.
(assuming that your API is available on port 3000), you will see that the necessary response headers are added. AJAX requests from http://localhost:81
should also work.
这篇关于如何将 CORS 添加到 compojure-api 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!