Reputation: 4383
My simple http-kit server:
(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 "/"))))
Every time I make a call from my JS app I'm getting a CORS error despite setting up wrap-cors
Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:9500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Upvotes: 1
Views: 944
Reputation: 55
The answer may lie in your comment.
wrap-cors is actually working, the problem seems to be that when I include :headers {:authorization (basic-auth-header email password)} in the client side code, the request to the backend fails. –
This would work. :access-control-allow-headers ["Content-Type" "Authorization"]
.
By the way, I want to ask if your code in your question is the actual code in your application. If you use some kind of authentication middleware, you shoud add wrap-cors
before the auth middleware. Browsers doesn't include "Authentication" header in preflight OPTIONS request automatically then requests fail. To make wrap-cors first may solve your problem.
Browser devtool will also help your debugging. You can see preflight requests and response in Network tab in Chrome devtool.
Upvotes: 0
Reputation: 91544
Here's a working example from our site including all the headers I needed to pass:
{"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"}
I cut out the application specific ones. You may need to include more such as X-My-Auth-Thing
in the headders section.
Upvotes: 1