Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda