I started development mode in Next.js 12. Frontend was started on localhost:3000, backend on another port and it was with a docker, nginx and php. All works well, but when I don’t set headers in request. When I added custom header or Authorization header – it crashed by CORS policy.
I added all CORS policy with a signment *. I stuck with this issue already 3 days.
To reproduce:
const response = axios.get('https://api.publicapis.org/entries', {
headers: {
'X-Custom-Header': 'foobar'
},
params: data,
}).then(res => {
console.log(res);
})
Screenshot:
https://disk.yandex.ru/i/YmPDH6pEdfem6A
Video:
2
Answers
It causes by sent request on another submdomain/domain. Now I just send it to the same domain.
The reason you get the error in the browser is that CORS is a method to restrict browsers. Servers respond however they want to, unrestricted, unless programmed to specifically look at the Origin header.
In response to the pre-flight try using these headers:
Access-Control-Allow-Origin: https://your.domain
(don’t use *, this doesn’t work with credentials)Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization
(or whichever other custom headers you add)Access-Control-Allow-Methods: GET, POST
(or whichever method you want to use)