Home > Enterprise >  name argument is required to req.get
name argument is required to req.get

Time:11-16

I have a nodejs server and a react frontend running on different instances. The frontend runs well without errors while the server returns this error after a successful login to my page

    TypeError: name argument is required to req.get
        at IncomingMessage.header (/home/tech/Desktop/REST/node_modules/express/lib/request.js:67:11)
        at module.exports (/home/tech/Desktop/REST/middleware/is-auth.js:5:28

I believe this part of my code is responsible for the error generation:

//extract token from frontend/client
module.exports = (req, res, next) => {
    const authHeader = req.get('');
    if (!authHeader) {
        const error = new Error('Not Authenticated');
        error.statusCode = 401;
        throw error;
    }
    const token = authHeader.split(' ')[1];
    let decodedToken;
    try {
        decodedToken = jwt.verify(token, 'secret'); //secret is used to validate token
    } catch (err) {
        err.statusCode = 500;
        throw err;
    }

Here is how I'm passing the token to the server

//pass token to the server
    fetch('http://localhost:8080/feed/posts?page='   page, {
      headers: {
        Authorization: 'Bearer '   this.props.token
      }
    })

CodePudding user response:

your middleware code should be updated, get the authorization header from request

//extract the token from the frontend/client
module.exports = (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader) {
        const error = new Error('Not Authenticated');
        error.statusCode = 401;
        throw error;
    }
    const token = authHeader.split(' ')[1];
    let decodedToken;
    try {
        decodedToken = jwt.verify(token, 'secret'); //secret is used to validate token
    } catch (err) {
        err.statusCode = 500;
        throw err;
    }
  • Related