Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!