score:30

Accepted answer

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*',
          },
        ]
      },
  };

score:0

i have next.js application that has graphql and apollo client setup (apollo version : 3.5.10). in order to make a query inside any component you have to use "client" variable that apollo client provide. you need to have apollo-client.js file in your project root so that apollo client can use it inside any component for query. inside any component when you trying to make a query like: client.query(...), with these settings of apollo-client file it will throw "cors" error. however you can fix this by adding headers property inside apollo-client file.

this is old settings:

apollo-client.js (old)

import { apolloclient, inmemorycache } from '@apollo/client';

const client = new apolloclient({
  uri: 'http://localhost:4000/graphql',
  cache: new inmemorycache(),
});

export default client;

this is new settings:

apollo-client.js (new)

import { apolloclient, inmemorycache } from '@apollo/client';

const client = new apolloclient({
  uri: 'http://localhost:4000/graphql',
  cache: new inmemorycache(),
  headers: {
    fetchoptions: {
      mode: 'no-cors',
    },
  },
});

export default client;

by doing this, you won't get any "cors" error while doing query inside any component.

score:1

please make sure it is cors and is not something else. for example, in my case i was getting a 400 response. please look on the response tab of that request for information.

score:1

do an extra check if your base url is correct that was my issue

score:3

it was a problem in the server not accepting options requests, because routes were declared as get::sometnig or post:: something, so the preflight couldn't 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();
});

score:4

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)
  }

score:4

if you want to use the cors library in nextjs, i created a library for it is nextjs-cors.

https://www.npmjs.com/nextjs-cors

https://github.com/yonycalsin/nextjs-cors

pages/api/whoami.{ts,js}

import nextcors from 'nextjs-cors';

async function handler(req, res) {
   // run the cors middleware
   // nextjs-cors uses the cors package, so we invite you to check the documentation https://github.com/expressjs/cors
   await nextcors(req, res, {
      // options
      methods: ['get', 'head', 'put', 'patch', 'post', 'delete'],
      origin: '*',
      optionssuccessstatus: 200, // some legacy browsers (ie11, various smarttvs) choke on 204
   });

   // rest of the api logic
   res.json({ message: 'hello nextjs cors!' });
}

Related Query

More Query from same tag