Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Why doesn't this middleware for preflight request work?

I know the post request will launch a preflight request before the actual post request send. So I made a middleware to handle all the preflights in Express like this:

/app.js:

const express=require('express');
const preflightRouter=require('./routes/preflight');

const app=express();

app.use(preflightRouter);  // *    preflightRouter is the middleware handling all the preflight requests.
app.post('/post', (req, res)=>{
    res.header('Access-Control-Allow-Origin', '*');
    res.send('Post requests successful.')
})

app.listen(5000, ()=>{
    console.log('server running on port 5000');
})

/routes/preflight:

const express=require('express');
const router=express.Router();

router.options('/', (req, res)=>{
    res.setHeader("Access-Control-Allow-Origin","*")
    res.setHeader("Access-Control-Allow-Headers", "*");
    console.log('Preflight hit.')
    res.end();
})

module.exports=router;   

It got CORS error:enter image description here

However, if change the * line to this, it works:

app.use('/post',preflightRouter);

I wondering why it has to perfectly match the entire route path? Isn't it "middleware mounted without a path will be executed for every request to the app" as the express tutorial says?

For completeness, here's the code of front web (frontend port 5500, backend port 5000):

<html>
    <head>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        <button id='btn'>POST</button>
        <script>
            btn.onclick=()=>{
                axios.post('http://localhost:5000/post', {name: 'Smith'})
                .then(response=>{
                    console.log(response);
                })
            }
        </script>
    </body>
</html>
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda