Vasco Ferreira
Vasco Ferreira

Reputation: 2363

REST API CORS error when trying to access it from a web application

I'm developing a web app with re-frame (lein new re-frame <app-name> +routes) and now I want to get data from a database. Since I'm using Clojurescript, I thought about creating an API with Clojure (lein new luminus <api-name> +postgres +service) and connect to my Postgres database.

Although both apps run and work, the AJAX requests fail due to CORS error.

My re-frame app is running on localhost:3449 and my API app is running on localhost:3000/api.

How can I get past this error? I don't know where to put the {"Access-Control-Allow-Origin" "*"}

Upvotes: 1

Views: 1175

Answers (1)

Vasco Ferreira
Vasco Ferreira

Reputation: 2363

With the help of squiresuzuki on Clojure Reddit, who pointed me to read about middlewares, I made this API to work by creating a middleware that adds the necessary headers to allow Cross Origin requests.

In the file middleware.clj I've change to the following:

(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)))))))

Upvotes: 1

Related Questions