Search code examples
clojurecorscompojurering

How to use CORS with JSON Response in Compojure?


I am creating a simple API which returns JSON data back to the user. For development purposes, I would like to enable CORS so that my react frontend can call the API locally. For the moment, it complains

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:3001' is therefore not allowed access.

Question: How can I use ring-cors (or something similar) to enable CORS and send back JSON data?

Observations: With the current (app ..), (wrap-cors ...) provides no cross origin header.

I have tried several variations of the order but none seem to work. For instance, (wrap cors ...) followed by (wrap-defaults ...) doesn't work.

MWE

(ns qitab-api.handler
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
            [ring.middleware.json :refer [wrap-json-response wrap-json-body]]
            [ring.middleware.cors :refer [wrap-cors]]
            [ring.util.response :as r]))

(defroutes app-routes
   (GET "/" []
     (r/response {:hello "World!!"}))
   (route/not-found "Not Found"))

(def app
  (-> app-routes
      wrap-json-body
      wrap-json-response
     (wrap-defaults site-defaults)
     (wrap-cors :access-control-allow-origin [#".*"] :access-control-allow-
     headers [:get])))

P.S. I have looked at several other questions which relate to CORS and Compojure however, none of them deal with the JSON aspect.


Solution

  • :access-control-allow-headers should be :access-control-allow-methods. Then it should work.