发布请求时出现Clojure Access-Control-Allow-Origin错误

时间:2015-07-24 10:30:15

标签: clojure cors clojurescript

我有一个简单的clojure后端在localhost:8090上运行,而一个简单的clojurescript前端在localhost:3449上运行。

我们的想法是,点击按钮后,前端会向后端的API端点发送POST请求并执行相应的操作。如果我使用邮递员并向后端发送请求,那么一切都按预期工作。

问题在于发送此请求时(使用cljs-http

(defn send-data []
    (http/post "http://localhost:8090/send-email" {:json-params {:subject "post from cljs"}}))

Chrome控制台报告:

XMLHttpRequest cannot load http://localhost:8090/send-email. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3449' is therefore not allowed access. The response had HTTP status code 404.

根据我的理解,我需要在我的应用程序中定义CORS,我这样做here这样做的问题是,一旦实现这一点,邮递员的POST请求就不再了工作,这打破了应用程序。

我的应用程序定义如下:

(defroutes app-routes
  (GET "/" [] (redirect "/index.html"))
  (GET "/emails" [] "emails")

  (POST "/send-email" {body :body} (do
                                     (send-email (json/read-str (slurp body)
                                                   :key-fn keyword))
                                     "OK"))
  (POST "/add-recipient" {body :body} (do
                                        (add-recipient (json/read-str (slurp body)
                                                         :key-fn keyword))
                                        "Recipient Added"))
  (route/not-found "Not Found"))

(def app
  (->
    (wrap-defaults app-routes api-defaults)
    (wrap-resource "public")
    (wrap-resource "/META-INF/resources")
    ))

我还尝试了基于Ring CORS github页面的配置:

(def app
  (->
    (wrap-defaults app-routes api-defaults)
    (cors/wrap-cors my-routes :access-control-allow-origin [#".*"]
                         :access-control-allow-methods [:get :put :post :delete])
    (wrap-resource "public")
    (wrap-resource "/META-INF/resources")
    ))

甚至不会编译Caused by: java.lang.IllegalArgumentException: No value supplied for key: [:get :put :post :delete]

如何实施它,以便它接受来自localhost:3449的请求,该请求会在不破坏当前功能的情况下发送JSON帖子正文。

编辑:

这些是邮递员在执行请求时的响应标头:

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

Response headers 
Date: Fri, 24 Jul 2015 10:07:31 GMT 
Access-Control-Allow-Origin: http://localhost:3449
Content-Type: text/html;charset=UTF-8 
Content-Length: 2 
Server: Jetty(7.6.13.v20130916) 

1 个答案:

答案 0 :(得分:0)

什么是my-routes

尝试

(-> app-routes 
  (wrap-defaults api-defaults)
  (cors/wrap-cors :access-control-allow-origin [#".*"]
                  :access-control-allow-methods [:get :put :post :delete])
  (wrap-resource "public")
  (wrap-resource "/META-INF/resources")
)