diff --git a/src/ring/middleware/cors.clj b/src/ring/middleware/cors.clj index e48bac8..ecd35d4 100644 --- a/src/ring/middleware/cors.clj +++ b/src/ring/middleware/cors.clj @@ -42,12 +42,13 @@ (defn add-access-control "Add the access control headers using the request's origin to the response." [request response access-control] - (if-let [origin (origin request)] - (update-in response [:headers] merge - (->> origin - (assoc access-control :access-control-allow-origin) - (normalize-headers))) - response)) + (if ((complement nil?) response) + (if-let [origin (origin request)] + (update-in response [:headers] merge + (->> origin + (assoc access-control :access-control-allow-origin) + (normalize-headers))) + response))) (defn wrap-cors "Middleware that adds Cross-Origin Resource Sharing headers. diff --git a/test/ring/middleware/cors_test.clj b/test/ring/middleware/cors_test.clj index 74843dc..4b8e262 100644 --- a/test/ring/middleware/cors_test.clj +++ b/test/ring/middleware/cors_test.clj @@ -4,7 +4,7 @@ (deftest test-allow-request? (testing "with empty vector" - (is (not (allow-request? {:headers {"origin" "http://eample.com"}} + (is (not (allow-request? {:headers {"origin" "http://example.com"}} {:access-control-allow-origin []})))) (testing "with one regular expressions" (are [origin expected] @@ -72,9 +72,25 @@ (deftest test-no-cors-header-when-handler-returns-nil (is (nil? ((wrap-cors (fn [_] nil) - :access-control-allow-origin #".*example.com") + :access-control-allow-origin #".*example.com") {:request-method - :get :uri "/" + :get :uri "/" + :headers {"origin" "http://example.com"}})))) + +(deftest test-no-cors-header-when-handler-returns-nil-and-matching-methods-supplied + (is (nil? ((wrap-cors (fn [_] nil) + :access-control-allow-origin #".*example.com" + :access-control-allow-methods [:get]) + {:request-method + :get :uri "/" + :headers {"origin" "http://example.com"}})))) + +(deftest test-no-cors-header-when-handler-returns-nil-and-unmatching-methods-supplied + (is (nil? ((wrap-cors (fn [_] nil) + :access-control-allow-origin #".*example.com" + :access-control-allow-methods [:post]) + {:request-method + :get :uri "/" :headers {"origin" "http://example.com"}})))) (deftest test-options-without-cors-header