title: Why doesn't this middleware for preflight request work?
body: <p>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:</p>
  <p>/app.js:</p>
  <pre><code>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)=&gt;{
      res.header('Access-Control-Allow-Origin', '*');
      res.send('Post requests successful.')
  })
  
  app.listen(5000, ()=&gt;{
      console.log('server running on port 5000');
  })
  </code></pre>
  <p>/routes/preflight:</p>
  <pre><code>const express=require('express');
  const router=express.Router();
  
  router.options('/', (req, res)=&gt;{
      res.setHeader(&quot;Access-Control-Allow-Origin&quot;,&quot;*&quot;)
      res.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;*&quot;);
      console.log('Preflight hit.')
      res.end();
  })
  
  module.exports=router;   
  </code></pre>
  <p>It got CORS error:<a href="https://i.stack.imgur.com/PD13L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PD13L.png" alt="enter image description here" /></a></p>
  <p>However, if change the * line to this, it works:</p>
  <pre><code>app.use('/post',preflightRouter);
  </code></pre>
  <p>I wondering why it has to perfectly match the entire route path? Isn't it &quot;middleware mounted without a path will be executed for every request to the app&quot; as the express tutorial says?</p>
  <p>For completeness, here's the code of front web (frontend port 5500, backend port 5000):</p>
  <pre><code>&lt;html&gt;
      &lt;head&gt;
          &lt;script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;button id='btn'&gt;POST&lt;/button&gt;
          &lt;script&gt;
              btn.onclick=()=&gt;{
                  axios.post('http://localhost:5000/post', {name: 'Smith'})
                  .then(response=&gt;{
                      console.log(response);
                  })
              }
          &lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>