reactjs – NextJs CORS issue

reactjs – NextJs CORS issue

I found a solution here:

Basically, I just need to add a next.config.js file in the root directory and add the following:

// next.config.js
module.exports = {
    async rewrites() {
        return [
          {
            source: /api/:path*,
            destination: https://api.example.com/:path*,
          },
        ]
      },
  };

it was a problem in the server not accepting OPTIONS requests, because routes were declared as GET::sometnig or POST:: something, so the preflight couldnt pass and the POST request was decliend, hope this will help another people to prevent hours of googling, so in my case (Node.js + Express.js) i had to add this to my server.js

  app.use((req, res, next) => {
    res.header(Access-Control-Allow-Origin, *);
    res.header(
      Access-Control-Allow-Headers,
      Origin, X-Requested-With, Content-Type, Accept, Authorization
    );
  if (req.method == OPTIONS) {
    res.header(Access-Control-Allow-Methods, PUT, POST, PATCH, DELETE, GET);
    return res.status(200).json({});
  }

  next();
});

reactjs – NextJs CORS issue

I had a similar issue, I was making the call from this page:

pages/page1.js

  export default async function page1() {
       const data = await axios.post(https://www.dominio.com/xxx , {param: 1}, headers)
}

But the solution is to make axios calls to a local API file inside pages/api directory, and this local API file, will handle the request to the external webserver. This avoid the CORS issue.

pages/page1.js

export default async function page1() {
        const data = await axios.post(/api/get_page1_data, {param: 1} )
}

pages/api/get_page1_data.js

export default async function handler(req, res) {
try{
   const data = await axios.post(https://www.dominio.com/xxx , {param: req.body.param}, headers)
    res.status(200).json(data)
 } catch (error) {
    console.error(error)
    return res.status(error.status || 500).end(error.message)
  }

Leave a Reply

Your email address will not be published.