React APP error with CORS and fetch from an Rest API

React APP error with CORS and fetch from an Rest API
typescript
Ethan Jackson

I am working on an assignment and have gotten this CORS issue when trying to post to the API. I have been trying to fix the cors error

server.js:

const corsOptions = { origin: process.env.FRONTEND_URL, // Allow requests from the frontend URL credentials: true, // Allow cookies and credentials methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers }; app.use(cors(corsOptions)); app.options('*', cors(corsOptions));

For reference, I am going to provide the fetch for my register page:

const response = await fetch(`${BACKEND_URL}/api/auth/register`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ username, email, password }), });

I am trying to make sure I can register but I keep failing with an error 401

Answer

The 401 error isn't necessarily from CORS, but rather from your auth endpoint. Either you have to have an unauthenticated endpoint to register, then redirect/respond with the token/auth mechanism of your choice, or you have to have a general client "secret" token that has the permissions necessary that can access the "public" endpoints like register, login, etc.

Related Articles