express cors policy no 'access-control-allow-origin'

Install the CORS middleware

First, install the cors middleware package using npm, by running the command npm install cors in your terminal.

Include the CORS middleware in your Express app

Next, require the cors package at the top of your Express application file using const cors = require('cors');.

Use the CORS middleware in your Express app

Then, use the cors middleware in your Express application by calling app.use(cors()); before defining your routes. This will enable CORS for all routes in your application.

Set specific CORS options if needed

If you need to set specific CORS options, you can pass an options object to the cors function when setting it up, such as app.use(cors({ origin: 'http://example.com' }));.

Handle CORS preflight requests

For handling CORS preflight requests (OPTIONS), you can set up a specific route to handle these requests, for example:

app.options('/*', cors());

This will allow the preflight requests to be handled by the cors middleware.

Test the CORS policy

Finally, test the CORS policy by making requests to your Express app from a different origin to ensure that the CORS headers are being set correctly.