score:30
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!' });
}
Source: stackoverflow.com
Related Query
- NextJs CORS issue
- Axios having CORS issue
- webpack dev server CORS issue
- How to overcome the CORS issue in ReactJS
- CORS Issue with React app and Laravel API
- How do I fix CORS issue in Fetch API
- Request fails due to CORS issue with origin from localhost
- CORS issue with Django and React hosted on same server
- S3 upload with presigned URLs and CORS Issue
- Keycloak CORS issue associated with login redirect
- Gatsby Module Federation CORS error and eager consumption issue
- Cannot get Signal R working due to cors issue - blocked by cors policy
- NextJS dynamic import issue
- CORS issue making AJAX request from React app > Node server > redirect to Google OAuth2 auth
- CORS issue - Response to preflight request doesn't pass access control check:
- CORS Issue With Ktor Backend
- CORS issue when trying to do JQuery post with json data, but not with plain text or x-www-form-urlencoded
- Issue with Static HTML Export in NextJS
- CORS issue with Restify
- Issue with :global() css-module selectors not being pure in NextJS
- cors issue with passport.js google oauth strategy
- CORS issue in codeigniter 4: Response to preflight request doesn't pass access control check
- Set-cookie not working for cross-site request / response in Dot net Core 3.1 & React setup same-site cookies and/or CORS issue
- Cors issue with response to preflight request
- NextJS issue reading items already in local storage
- CORS issue using create-react-app when trying to use an image from another URL
- Nextjs Bootstrap Dropdown issue with server side rendering
- Laravel 8 CORS issue with React Axios
- CORS 'Access-Control-Allow-Origin' header not present issue
- Cors Issue with React Frontend and Django Backend
More Query from same tag
- How to limit number of checkboxes to certain number in react?
- ReactJS - Component not passing this.state.object properly to another component
- Sort column based on property im passing to a Cell
- wait for loading paypal script in nextjs page
- React redux First object missing on rendering when data is entered in the text field
- setting the state with the switch instruction in the react
- re-render as soon as the state is changed
- Rendering all nested objects from object in React
- Multiple input onChange issue
- How to properly get message count on form submission using reactjs
- React state not updating
- Animate current value += something in React Spring
- Hosting create-react-app on gh-pages
- Displaying time data on horizontal calendar
- reactjs need data from MySQL add before code can resume - can I use a 'then' somewhere
- How can I use init state without using Provider and connect() in Redux
- How to fix cannot GET on page hard refresh using CTRL+shift+R in Reactjs
- React set className by conditions dynamic
- Array.fill().map() is not working in react
- react - How to open show more on a function component?
- How to pass object to hashHistory.push() in react
- How to use plugins with chartist.js?
- How to set state with spread operators, when using variables for keys?
- JS fetch unable to set headers
- Fetching API data, nested in two arrays and displaying it with React
- How to use object that I am getting as string in props
- Material UI Autocomplete with Avatar in textfield
- Switch array objects onClick
- Reactjs ag-grid Module conversion - Module[] is not assignable to type (/ag-grid-community/dist/lib/interfaces/iModule).Module[]
- React with Material UI not finding custom font