Home > Enterprise >  How can I fix not defined error? NodeJS, JWT
How can I fix not defined error? NodeJS, JWT

Time:08-22

const express = require("express");
const jwt = require("jsonwebtoken");
const { type } = require("os");

const app = express();

app.get("/api", (req,res) => {
    res.json({
        message: "Welcome to the API"
    });
});

app.post("/api/posts", (req,res) => {
    res.json({
        message: "Post has been created.."
    });
});

app.post("/api/login", verifyToken, (req,res) => {
    // Mock User
    const user = {
        id: 24,
        username: "Jonah",
        email: "[email protected]"
    }

    jwt.sign({user}, "secretkey", (err, token) => {
        res.json({
            token
        });
    });
});  

// Verify Token
function verifyToken(req,res,next) {
    // Get authorization header value
    const bearerHeader = req.headers["authorization"];
}
    // Check if bearer is undefined
if(typeof bearerHeader !== "undefined") {

}else{
    // Forbidden
    res.sendStatus(403);
}

app.listen(5000, () => console.log("Server is listening on port 5000.."));

I want to make Node.js API Authentication With JWT and when I check this with if/else method I get an error that is saying "res is not defined", how can I defined this "res" and fix the error?

res.sendStatus(403); ^

ReferenceError: res is not defined

CodePudding user response:

You have some improper bracing in your verifyToken() function. Change this:

// Verify Token
function verifyToken(req,res,next) {
    // Get authorization header value
    const bearerHeader = req.headers["authorization"];
}
    // Check if bearer is undefined
if(typeof bearerHeader !== "undefined") {

}else{
    // Forbidden
    res.sendStatus(403);
}

to this:

// Verify Token
function verifyToken(req,res,next) {
    // Get authorization header value
    const bearerHeader = req.headers["authorization"];
    // Check if bearer is undefined
    // FIX THIS: need to not just check if it's undefined, but if
    //    its valid
    if(typeof bearerHeader !== "undefined") {
        next();
    } else {
        // Forbidden
        res.sendStatus(403);
    }
}
  • Related