Ошибка происхождения Clojure - полностью потеряна - PullRequest
0 голосов
/ 20 сентября 2019

У меня есть следующий простой сервер в Clojure, использующий Compojure (что немного напоминает шаблон звонка).В разработке все работало нормально, и теперь, когда я в разработке, я не могу заставить CORS работать на всю жизнь - у меня есть функция wrap-preflight, которая, кажется, работает нормально, но я продолжаю получать ошибки CORS в терминалеи ни почта, ни получение запросов на мою систему комментариев не работают.Я полностью потерян и очень расстроен, я спрашивал вокруг, и никто, кажется, не знает.

Вот основной core.clj код - Если у кого-то есть идеи , пожалуйста, , дайте мне знать.Вы можете увидеть ошибки в прямом эфире на thedailyblech.com (не реклама, но, возможно, это поможет отладить).

Спасибо!

(ns clojure-play.core
  (:use     org.httpkit.server
            [compojure.core :refer :all]
            [compojure.route :as route]
            [clojure.data.json :as json]
            [clojure.tools.logging :only [info]]
            [clojure-play.routes :as routes]
            [ring.middleware.json :only [wrap-json-body]]
            [ring.middleware.cors :refer [wrap-cors]])
  (:require [monger.core :as mg]
            [monger.collection :as mc]
            [clojure.edn :as edn]
            [clojure.java.io :as io]
            [compojure.handler :as handler])
  (:import [org.bson.types ObjectId]
           [com.mongodb DB WriteConcern])
  (:gen-class))
(println "in the beginning was the command line...")

(defonce channels (atom #{}))

(defn connect! [channel]
  (info "channel open")
  (swap! channels conj channel))

(defn notify-clients [msg]
  (doseq [channel @channels]
    (send! channel msg)))

(defn disconnect! [channel status]
  (info "channel closed:" status)
  (swap! channels #(remove #{channel} %)))


(defn ws-handler [request]
  (with-channel request channel
    (connect! channel)
    (on-close channel (partial disconnect! channel))
    (on-receive channel #(notify-clients %))))

(defn my-routes [db]
  (routes
   (GET "/foo" [] "Hello Foo")
   (GET "/bar" [] "Hello Bar")
   (GET "/json_example/:name" [] routes/json_example)
   (GET "/json_example" [] routes/json_example)
   (POST "/email" [] routes/post_email)
   (POST "/write_comment" [] (fn [req] (routes/write_comment req db)))
   (POST "/update_comment" [] (fn [req] (routes/update_comment req db)))
   (GET "/read_comments/:path" [path] (fn [req] (routes/read_comments req db path)))
   (GET "/read_comments/:path1/:path2" [path1 path2] (fn [req] (routes/read_comments req db (str path1 "/" path2))))
   (GET "/ws" [] ws-handler)))

(defn connectDB []
  (defonce connection
    (let
     [uri "mongodb://somemlabthingy"
      {:keys [conn db]} (mg/connect-via-uri uri)]
      {:conn conn
       :db db}))
  {:db (:db connection)
   :conn (:conn connection)})

(def cors-headers
  "Generic CORS headers"
  {"Access-Control-Allow-Origin"  "*"
   "Access-Control-Allow-Headers" "*"
   "Access-Control-Allow-Methods" "GET POST OPTIONS DELETE PUT"})

(defn preflight?
  "Returns true if the request is a preflight request"
  [request]
  (= (request :request-method) :options))

(defn -main
  "this is main"
  [& args]

  (println "hello there main")

  (def db (get (connectDB) :db))

  (println (read-string (slurp (io/resource "environment/config.edn"))))


  (defn wrap-preflight [handler]
    (fn [request]
      (do
        (println "inside wrap-preflight")
        (println "value of request")
        (println request)
        (println "value of handler")
        (println handler)
        (if (preflight? request)
          {:status 200
           :headers cors-headers
           :body "preflight complete"}
          (handler request)))))

  (run-server
   (wrap-preflight
    (wrap-cors
     (wrap-json-body
      (my-routes db)
      {:keywords? true :bigdecimals? true})
     :access-control-allow-origin [#"http://www.thedailyblech.com"]
     :access-control-allow-methods [:get :put :post :delete :options]
     :access-control-allow-headers ["Origin" "X-Requested-With"
                                    "Content-Type" "Accept"]))
   {:port 4000}))

Ответы [ 2 ]

3 голосов
/ 20 сентября 2019

Промежуточное программное обеспечение CORS автоматически обрабатывает предварительные данные - вам не нужно отдельное промежуточное программное обеспечение для него, и вам не нужно создавать свои собственные заголовки и т. Д.

У вас есть оно, обертывающее routes, что правильно- поэтому сначала выполняется CORS-проверка, а затем маршрутизация.Вы должны удалить ваше пользовательское промежуточное ПО для предварительной проверки, и оно должно работать в этот момент.

Мы используем wrap-cors на работе, и единственное осложнение, с которым мы столкнулись, - это предоставление достаточного количества заголовков (некоторые вставляются производственной инфраструктурой, например, балансировщиками нагрузки),Мы закончили с этим:

                           :access-control-allow-headers #{"accept"
                                                           "accept-encoding"
                                                           "accept-language"
                                                           "authorization"
                                                           "content-type"
                                                           "origin"}

Для чего это стоит, вот что у нас есть для методов:

                           :access-control-allow-methods [:delete :get
                                                          :patch :post :put]

(вам не нужно :options там)

1 голос
/ 20 сентября 2019

Возможно, стоит попытаться добавить явный маршрут

(OPTIONS "/*" req handle-preflight)

к вашим маршрутам Compojure - в моем случае именно это заставило его работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...