CORS preflights error when using redirect

184 Views Asked by At

I`m trying to realize redirecting to another page of my app (current location 'http://localhost:3000/create-item' redirect to 'http://localhost:3000/subscribe') after saving item to database on my express server using next code (client send POST message to endpoint with form data):

await item.save(); 
 res.writeHead(302, { Location: 'http://localhost:3000/subscribe' });
 res.end();

one more variant:

await item.save();
res.redirect('/subscribe');

In base file of my server index.js i use my custom CORS middleware:

//cors.middleware.js
function cors(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, PUT, PATCH, POST, DELETE, OPTIONS');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization',
  );
  next();
}
module.exports = cors;

//index.js
const corsMiddleware = require('./middleware/cors.middleware');
app.use(corsMiddleware);

I also tryed:

 npm i cors
    app.use(cors()); 

Nevertheless I recieve CORS error while redirecting. So, what I`m doing wrong? Maybe this is related to sending data with POST method (redirect inside GET endpoint working well without CORS erro)

0

There are 0 best solutions below