Error with CORS when requesting users

Question:
I’m attempting to display a table listing users returned from my MongoDB Atlas. However, I keep getting a couple errors in the console.

First error: Access to XMLHttpRequest at ‘{url}/users’ from origin ‘{replitURL}’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Second error: devtools.js:109 Error fetching users: st {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …}

I have the cors package installed and am requiring it in my index.js, and have explicitly declared requests from anywhere should be allowed, but I’m still getting this error.

I will note that console.log users is working, so I do see that data, but I cannot figure out how to successfully render that data in the table of the root view.

Repl link:
https://replit.com/@majornorth/indexjs

code snippet

In your express app, you have cors middleware, which helps protect your app from from requests from other sites (usually preventing CSRF, with exceptions).

Anyway, the way express handles middleware/routes is the way it is handled in your code. When sending a request, the browser sends a preflight request to check if it is safe. This goes through the cors handler before it goes to your route, which rejects before it can reach the /users route.

TLDR: move the /users route to the top, before app.use(cors());. (Also make sure to move the app.use(bodyParser.json()); further above this).

Also Note: consider changing res.setHeader('Access-Control-Allow-Origin', '*'); to the appropriate domain rather than *, since this can cause security vulnerablities.

Other Tips:

  • app.get("/users", cors({origin: "mongodb-url"}), (req, res) => { is a more appropriate of using cors
  • Don’t send the catched error to the client, instead, log it. Having this exposes details about your application and could potentially reveal sensitive information.

A lot of these tips may seem irrelevant in your specific application but they are best practises, because they will apply to other applications with such risks.

Actually, there was nothing wrong with the code. I paired with another engineer and it turns out that Replit is causing the networking error. I migrated my codebase to codesandbox.io and the exact same code works (the only line I changed is line 9 in HomePage.js: .get(“http://localhost:3000/users”) and it ran find.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.