我正在开发一个带有re-frame (lein new re-frame <app-name> +routes
)的web应用程序,现在我想从数据库中获取数据。因为我使用的是Clojurescript,所以我想用Clojure (lein new luminus <api-name> +postgres +service
)创建一个API并连接到我的Postgres数据库。
虽然这两个应用程序都运行并正常工作,但AJAX请求由于CORS错误而失败。
我的re-frame应用程序在localhost:3449
上运行,我的API应用程序在localhost:3000/api
上运行。
我怎样才能克服这个错误?我不知道该把{"Access-Control-Allow-Origin" "*"}
放在哪里
发布于 2019-06-27 10:45:22
在Clojure Reddit上的squiresuzuki
的帮助下,他指引我阅读关于中间件的文章,我通过创建一个中间件来使这个API工作,该中间件添加了必要的头来允许跨源请求。
在文件middleware.clj
中,我已更改为以下内容:
(defn wrap-cors
"Wrap the server response with new headers to allow Cross Origin."
[handler]
(fn [request]
(let [response (handler request)]
(-> response
(assoc-in [:headers "Access-Control-Allow-Origin"] "http://localhost:3449")
(assoc-in [:headers "Access-Control-Allow-Headers"] "x-requested-with, content-type")
(assoc-in [:headers "Access-Control-Allow-Methods"] "*")))))
(defn wrap-base [handler]
(-> ((:middleware defaults) handler)
(wrap-cors) ; enable CORS
(wrap-defaults
(-> site-defaults
(assoc-in [:security :anti-forgery] false)
(assoc-in [:session :store] (ttl-memory-store (* 60 30)))))))
https://stackoverflow.com/questions/56783213
复制相似问题