Clojure http-kit:CORS设置无效

时间:2019-07-01 17:21:44

标签: clojure clojurescript

我简单的http-kit服务器:

(ns figgy.core
  (:gen-class)
  (:require [org.httpkit.server :as server]
            [compojure.core :refer :all]
            [ring.middleware.cors :refer [wrap-cors]]
            [compojure.route :as route]))
(defn fps-handler [req]
  {:status  200
   :headers {"Content-Type" "text/html"}
   :body    "Pew pew!"})

(defn mail-man []
   "{\"Spongebob Narrator\": \"5 years later...\"}")

(defn mail-handler [req]
  {:status  200
   :headers {"Content-Type" "text/json"} ;(1)
   :body    (mail-man)}) ;(2)

(defn general-handler [req]
  {:status  200
   :headers {"Content-Type" "text/html"}
   :body    "All hail General Zod!"})

(defroutes app-routes ;(3)
  (GET "/" [] fps-handler)
  (POST "/postoffice" [] mail-handler)
  (ANY "/anything-goes" [] general-handler)
  (route/not-found "You Must Be New Here")) ;(4)

(def app
  (-> app-routes
    (wrap-cors
     :access-control-allow-origin [#".*"]
     :access-control-allow-headers ["Content-Type"]
     :access-control-allow-methods [:get :put :post :delete :options])))

(defn -main
  "This is our app's entry point"
  [& args]
  (let [port (Integer/parseInt (or (System/getenv "PORT") "8080"))]
    (server/run-server #'app {:port port})
    (println (str "Running webserver at http:/127.0.0.1:" port "/"))))

每次我从JS应用程序拨打电话时,尽管设置了 wrap-cors

,但都会收到CORS错误
  

从源访问“ http://localhost:8080/”处的XMLHttpRequest   “ http://localhost:9500”已被CORS政策屏蔽:对   预检请求未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源

2 个答案:

答案 0 :(得分:0)

这是我们网站上的一个可行示例,其中包括我需要传递的所有标头:

{"Access-Control-Allow-Origin" origin
 "Access-Control-Allow-Credentials" "true"
 "Access-Control-Allow-Methods" "POST, GET, OPTIONS, PUT, DELETE"
 "Access-Control-Allow-Headers" "Content-Type, Accept, Authorization, Authentication, If-Match, If-None-Match, If-Modified-Since, If-Unmodified-Since"}

我删去了特定于应用程序的内容。您可能需要在标题部分添加更多内容,例如X-My-Auth-Thing

答案 1 :(得分:0)

答案可能取决于您的评论。

  

wrap-cors实际上正在工作,问题似乎是当我在客户端代码中包括:headers {:authorization(basic-auth-header电子邮件密码)}时,对后端的请求失败。 –

这可以工作。 :access-control-allow-headers ["Content-Type" "Authorization"]

顺便说一句,我想问一下您所问的代码是否是您应用程序中的实际代码。如果您使用某种身份验证中间件,则应在身份验证中间件之前添加wrap-cors。浏览器在预检OPTIONS请求中不自动包含“ Authentication”标头,然后请求失败。首先制作自动包装纸可能会解决您的问题。

浏览器devtool也将帮助您进行调试。您可以在Chrome devtool的“网络”标签中查看预检请求和响应。