The request object you've provided shows that the preflight CORS request method is OPTIONS and indeed originates from . This request is trying to reach the endpoint on .
User
What are the differences between ajax.core and cljs-http.client when it comes to sending requests?
Your init function is the one responsible for initializing the app and calling mount-root to mount your components onto the page. While the provided code shows an attempt at rendering the components, there are a few adjustments and checks we should make to ensure the page renders correctly:
(defn ^:after-load on-reload []
;; Re-mount the app after code reloading occurs
(mount-app))
(defn set-session-cookie [response user-id]
(let [cookie-value (transforms/hash (str user-id) :crc32)] ; Generate a simple cookie value based on the user ID
(ring/set-cookie response "token" cookie-value {:max-age 3600}))) ; Set cookie with a maximum age of 1 hour
(GET "/new-game" request (new-game-handler request))
;; (GET "/guess:token" [token] (guess-page-handler token))
(GET "/guess" [guess :<< as-int :as request] (guess-handler guess (get-session-cookie request)))
(ANY "*" [] (not-found (str "Sorry, no such URI on this server!\n\n
Navigate to /new-game to start the guessing game.\n
If you're in the middle of a game, go to /guess/?guess=N instead."))))
This is the error when I try to send a login request:
Access to XMLHttpRequest at 'http://localhost:3000/api/login' 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.
xhrio.js:207
code
POST http://localhost:3000/api/login net::ERR_FAILED
Based on the error message you're seeing, it appears that your CORS (Cross-Origin Resource Sharing) setup on the server side is not correctly configured, causing the browser to block the request from the frontend running on http://localhost:9500 to the backend running on http://localhost:3000.
Here's a potential fix:
Make sure that your wrap-cors middleware settings correctly match the necessary conditions to accept requests from your front-end application's domain. In your handler definition, the wrap-cors function includes a regex to match against the Origin header for CORS preflight requests. However, these URLs are not matching or the headers are not being sent back correctly.
In your current wrap-cors settings, you have the following:
Additionally, make sure that your backend server is indeed sending back the necessary CORS response headers upon preflight OPTIONS requests. The error message you are seeing often indicates that the server did not include the Access-Control-Allow-Origin header in its response.
Debugging Steps:
Ensure that your OPTIONS route can correctly handle preflight requests. It should respond with the necessary CORS headers without requiring any authentication or session cookies.
Use tools like curl or Postman to make a preflight OPTIONS request to your API endpoint and examine the response headers. This will help you verify if the server is sending the correct CORS headers.
If you're using a browser to test, you can also check the Network tab in your browser's developer tools to look at the request/response details.
Make sure that your front-end code is actually sending the correct Origin header that matches what is expected by the backend during the preflight request.
Since the CORS middleware is placed after some other middlewares, ensure that those middlewares aren't affecting the request before it reaches the CORS middleware. You might want to place wrap-cors earlier in the middleware chain.
After making the changes, restart your backend server and try to make the login request again. If the server is configured correctly, it should include the Access-Control-Allow-Origin header in its responses, and the browser should allow the request from your frontend application.
http://localhost:9500
POST /api/login
http://localhost:3000
For CORS to work, the server must respond to this OPTIONS request by setting the Access-Control-Allow-Origin header (and potentially others) to indicate to the browser which origins are permitted.
Since your request object has an :origin header of "http://localhost:9500" and contains the access-control-request-method of "POST", you need to ensure your server responds to OPTIONS requests with the appropriate CORS headers that align with the frontend origin and requested method.
Looking at the provided middleware, wrap-cors should be correctly configured to handle the CORS headers. However, there might be an issue with the order in which middleware functions are being applied or the OPTIONS route may not be correctly handling the request.
Try altering your site-routes definition by specifically adding a route to handle OPTIONS requests for each path correctly. For example:
Ensure that options-routes is applied before your main site-routes, so the server can handle preflight OPTIONS requests before reaching specific POST or GET routes.
In your middleware stack, make sure that the wrap-cors middleware function is applied as one of the first in your chain to allow the CORS headers to be properly included in the responses for preflight requests.
After applying these changes, restart your server and retry the request from the frontend. This should provide the necessary CORS headers in the response to the browser preflight check and prevent the CORS policy error.
Both ajax.core and cljs-http.client are ClojureScript libraries that provide an interface for making HTTP requests from the client-side in a browser environment. They offer similar basic capabilities but have some differences in terms of API design, extra features, and underlying implementation.
Here's a comparison based on various factors:
ajax.core
ajax.core is part of the cljs-ajax library. It provides a straightforward and flexible API for making AJAX requests.
API Design: The API is designed to be succinct and easy to use. You can make simple requests with little boilerplate code.
Request Handling: It uses protocols to handle different response formats and can automatically decode the response into the appropriate Clojure data type based on the response MIME type.
Library Size: It might be smaller and simpler, making it easier to integrate into applications without adding significant overhead.
Abstractions: cljs-ajax uses nice ClojureScript idioms and provides higher-level abstractions for handling asynchronous behavior, such as core.async channels and using cljs.core.async for response handling.
Interceptors: Offers a system of "interceptors" that allows tweaking requests and responses at various stages of processing.
Error Handling: Error handling can be done using the :handler and :error-handler functions provided with the AJAX call.
Promises: While not natively supporting promises, it can be easily integrated with core.async or other promise libraries.
cljs-http.client
cljs-http.client is a library for making HTTP requests that aims to provide a more idiomatic ClojureScript API.
API Design: Provides a ClojureScript API similar to that of the clj-http library on the server-side.
Request Handling: Also supports automatic encoding and decoding of request and response bodies.
Library Size: Might be relatively larger due to its attempt to mirror the server-side clj-http library.
Abstractions: Does not directly use core.async but returns results wrapped in core.async channels, making it convenient to integrate with asynchronous flows.
Interceptors: Does not have a built-in system of interceptors like cljs-ajax.
Error Handling: Responses, whether successful or unsuccessful, are returned in the same channel, and you need to check the status and handle errors appropriately.
Promises: While it natively works with channels, it can be adapted to work with JavaScript promises or other ClojureScript concurrency primitives.
Considerations for Choosing
If you prefer a consistent experience between client-side and server-side HTTP clients and are already familiar with clj-http, you might opt for cljs-http.client.
If you want a more concise API and like the use of core.async or need interceptors, you might choose ajax.core.
Consider the additional features each library offers that may be supportive of your particular use case.
One additional note is to consider community support, maintainability, and the frequency of updates for each library, which can be important factors when choosing which library to integrate into a long-term project. Both libraries are capable, and the best choice can depend on personal preferences, project requirements, and the developer's experience with ClojureScript.
Define main-panel: It seems you are trying to render views/main-panel in mount-root, but this is not defined in the provided spelling-bee-page function. You should either:
Ensure views/main-panel is correctly defined in spelling-bee.views namespace, or
Use spelling-bee-page directly if that's the main view of your app.
Check that events/initialize-db is correct: Your init function is dispatching this event to initialize the app's database. Make sure you have defined this event handler correctly in your events namespace.
Ensure app div exists: The mount-root function is trying to get an element with the ID app. Make sure your HTML file contains a div with this ID:
html
<div id="app"></div>
Call init at the right time: You need to call the init function after the page has loaded to ensure the JavaScript has access to the DOM when trying to mount the React component. This is usually done at the end of your ClojureScript file or inside a js/document.addEventListener for "DOMContentLoaded".
Assuming you have views/main-panel properly defined, here's a refined version of mount-root and a suggestion for calling init:
clojure
(defn mount-root []
(rf/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rdom/unmount-component-at-node root-el)
(rdom/render [views/main-panel] root-el)))
;; At the end of your ClojureScript file, you can add:
(set! (.-onload js/window) init)
Or, if you'd rather use spelling-bee-page:
clojure
(defn mount-root []
(rf/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rdom/unmount-component-at-node root-el)
(rdom/render [spelling-bee-page] root-el)))
;; And call `init` when the DOM is ready
(set! (.-onload js/window) init)
Make these adjustments and ensure that init is actually called when the page loads; your app should render the desired components. Remember to check the developer console for any warnings or errors if it still doesn't render as expected.