Search code examples
reactjscorsfetchvercel

Cors Issues in React project using Vercel


I have a react project, and yesterday I deployed it in vercel, now I have a CORS issue. Could you tell me how can I solve it? Thanks in advance.

Cors Issue

I want to deploy a react project using an API from Zoho Catalog. here my request.

  useEffect(()=>{ 
    const peticion = fetch(urlPost,{
      method: 'POST',
    });
    peticion
    .then((ans)=>{return ans.json()})
    .then((resp)=>{
      const reslt = resp.access_token;
      return fetch(urlGet,{
        method: "GET",
        headers:{
            'Authorization':`Zoho-oauthtoken ${reslt}`,
           }}
         )})
        .then((answer) => { return answer.json() })
        .then((resp) => {
          const result = resp.data
          setData(result)
          setFiltered(result)
        }) 
  },[])

Solution

  • There are 2 ways of dealing with it. The first method would be allowing cors in your server, if you have a nodejs server then you can add the following code into your server.js file

    const cors = require("cors")
    app.use(cors())
    

    if you don't have a nodejs server then you can google how to enable cors in the respective language your server is using. This only works if you have access to the server, if you don't have access to your server you can try the second method.

    The second method would be using a proxy server. You can follow this video on how to do it or you can read this post