Skip to content
Advertisement

Next.js and Express.js give CORS error, API queries only work at build time

I have a project where I use Next.js on the front-end and Express.js on the back.

Front-end side The ‘pages’ file contains ‘index.js’. In it, I am sending the following request.

JavaScript

Back-end side

JavaScript

And here is my Route code :

JavaScript

So, When the page is first built with Next.js, the api works, but when I click the ‘Load more’ button, it gives a CORS error. When I use the same query with ‘postman’ and other tools, it does not give any error. On the Next.js side, it works when I send a query to another 3rd party API., but it doesn’t work when I send it to my own back-end. And no matter what page or component I do this in, only the APIs that are created at the build time are working.

What could be the reason for this? and how can i solve it? I’ve read and searched a few articles about cors, but I still haven’t found a solution for days.

Advertisement

Answer

CORS should be placed on top level as javascript is executed one by one line. Place app.use(cors()) just above the line of app.use("/productlist", productlistRouter);

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement