oliyh / martian

The HTTP abstraction library for Clojure/script, supporting OpenAPI, Swagger, Schema, re-frame and more
MIT License
525 stars 42 forks source link

How do I set withCredentials header? #135

Closed rgkirch closed 2 years ago

rgkirch commented 2 years ago

I can't figure out how to set headers. I'm making a cors request and I need "withCredentials" to be false. This gives me a cors error.

(def m (martian-http/bootstrap "http://icanhazip.com"
                               [{:route-name :ip
                                 :path-parts []
                                 :method :get}]
                               {:interceptors (concat [{:name ::cors
                                                        :enter #(update-in % [:request :headers] merge {"withCredentials" "false"})}]
                                                      martian-http/default-interceptors)}))
(martian/request-for m :ip)
;; {:headers {"withCredentials" "false"}, :method :get, :url "http://icanhazip.com", :as :auto}

(go (println (<! (martian/response-for m :ip))))

cors error

Access to XMLHttpRequest at 'http://icanhazip.com/' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

This doesn't give me a cors error.

(require '[cljs-http.client :as client])
(go (println (<! (client/get "http://icanhazip.com" {:with-credentials? false}))))

Thanks!

oliyh commented 2 years ago

Hi,

You can let the http library do it for you, to make the request identical to your working example:

{:name ::cors
 :enter #(assoc-in % [:request :with-credentials?] false)}

The request map is passed directly to the http library, so it should work. Not sure if it does anything other than set the header like you were trying, but I'm guessing it does.

oliyh commented 2 years ago

(You were doing the right thing to set headers, as you saw from the request-for result, but I think just setting the header is not enough)

rgkirch commented 2 years ago

Thank you! Yea, associng :with-credentials? worked.