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;
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>