Delete request is not getting the Authorization header

66 Views Asked by At

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.

2

There are 2 best solutions below

0
Emad Mamaghani On

I would suggest 2 things:

  1. I have no idea what Request is! Make sure that the delete method of Request appends headers correctly.
  2. Inspect the network (using devTools) to see if the frontend is sending the request with specified headers.

Recommendation: use Fetch/Axios

0
NaguiHW On

The error was tha I was sending the header as the body. I had to put an empty object ({}) before the header.

export const deletePackageApi = id =>
  Request.delete(`/package/${id}`, {}, {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.getItem('user-token'),
  });