I have my backend in NodeJs and Express. 90% of my endpoints go through the validateToken middlewere and it works well, but I created a delete endpoint and for some reason it doesn't get the Authorization header even when I am sending it.
This is part of my code:
- Backend
// CORS
app.use(cors({
origin: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
}));
// Routes
router.delete('/package/:id', validateToken, isAdmin, deletePackage);
exports.validateToken = async (req, res, next) => {
try {
if (!req.headers.authorization) {
return res.status(401).send({error: 'Remember to include the Authorization header'});
}
const token = req.headers.authorization.split(' ')[1];
const decodedToken = await admin.auth().verifyIdToken(token);
if (!decodedToken) {
return res.status(401).send({error: 'Invalid token'});
}
req.user = decodedToken.email;
next();
} catch (error) {
return res.status(400).send({error: error});
}
};
- Frontend
export const deletePackageApi = id =>
Request.delete(`/package/${id}`, {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('user-token'),
});
This is the response that I am getting only with the delete request:
{error: 'Remember to include the Authorization header'}
I put it logs in the tha backend and only with the delete endpoint is not getting the Authorization header.
I would suggest 2 things:
Requestis! Make sure that thedeletemethod ofRequestappends headers correctly.Recommendation: use Fetch/Axios