4

cljs アプリ ( http://localhost:3000で実行) から Pedestal サーバー ( http://localhost:8080で実行) にリソースをリクエストしようとすると、以下のエラーが発生します。http://localhost:3000からの CORS を許可したい:

XMLHttpRequest cannot load http://localhost:8080/db/query. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

クライアントからのリクエストを送信するためにcljs-httpを使用しています。リクエストは次のようになります。

(defn load-server-data
  []
  (go
    (let [q (<! (http/post "http://localhost:8080/db/query"
                           {:edn-params {:query '[:find ?rep ?last
                                                  :where
                                                  [?rep :sales-rep/first-name ?last]]}}))]
      (println "q" q))))

のルートは/db/query次のようになります。

(defroutes routes
           [[["/db"
              {:post handlers/db-post}
              ["/query" {:post handlers/db-query}
               ^:interceptors [interceptors/edn-interceptor]]]]])

これは のハンドラです/db/query:

(defn db-query
  [req]
  (let [edn-params (:edn-params req)
        q (:query edn-params)
        args (:args edn-params)
        q-result (apply d/q q (d/db conn) args)]
    {:status 200
     :body   (pr-str q-result)}))

サーバーを実行するには、REPL でこの関数を実行します。

(defn run-dev
  "The entry-point for 'lein run-dev'"
  [& args]
  (println "\nCreating your [DEV] server...")
  (-> service/service
      (merge {:env                     :dev
              ::server/join?           false
              ::server/routes          #(deref #'service/routes)
              ::server/allowed-origins {:creds true :allowed-origins (constantly true)}})
      server/default-interceptors
      server/dev-interceptors
      server/create-server
      server/start))

Pedestal の CORS に関する情報はあまりないようです。私はcorsの例を見てきましたが、私のものはそうではありませんが、うまくいくようです。ルートに追加する必要がある別のインターセプターや、ここで欠落している何らかの構成設定はありますか?

4

2 に答える 2

3

私は問題を理解しました。エラーがスローされていたことが判明しましたが、デバッガーから飲み込まれて隠されていました。ハンドラー関数の周りに try catch を追加するだけで問題が解決します。

(defn db-query
  [req]
  (try
    (let [edn-params (:edn-params req)
          q (:query edn-params)
          args (:args edn-params)
          q-result (apply d/q q (d/db conn) args)]
      {:status 200
       :body   (pr-str q-result)})
    (catch Exception ex
      {:status 400
       :body   "Not authorized"})))
于 2015-10-28T05:46:49.317 に答える