kartikk221 / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
1.73k stars 89 forks source link

CORS error with nextjs, reactjs #305

Open slabworwide opened 2 days ago

slabworwide commented 2 days ago

Hello Author,I am facing cors error with below hyper-express api . please let me know how to resolve cors error.

Cors error comes when when headers passed to frontend api call. But if we write the below frontend code as a server action function in then error does not come. Since server does not require cors.
But when we write below frontend code including headers in client side , it throws error. If we remove the headers and method like below then cors error does not appear.

const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/user/${id}`)

hyper express->

router.use('/user',auth)
router.get('/user/:id', async (request, response) => {
       const id = request.path_parameters.id;
       const query = 'SELECT * FROM users WHERE id = id;
      const { rows } = await pool.query(query, [id]);
     response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
     response.json(rows);

})

frontend->

async function fetchSingleuser({id,session}){
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/user/${id}`,{
        method: 'GET',
        headers: {
          "Content-Type": "application/json",
            "Authorization": `Bearer ${session.access_token}`
        },

    })
    return res.json()
    }