Having trouble with JsonWebToken; JsonWebToken Error: JWT must be provided Having trouble with JsonWebToken; JsonWebToken Error: JWT must be provided express express

Having trouble with JsonWebToken; JsonWebToken Error: JWT must be provided


jwt must be provided

This error happens when the coming token is null or empty.


It may be you have not defined jwt in specific file or it is null or empty. Therefore you are getting an error. I just test your code and it works for me. It may be that you are not sending jwt token into post request correctly.

const express = require('express');const jwt = require('jsonwebtoken');const bodyParser = require('body-parser');const http = require('http');const api = express();api.use(bodyParser.json());api.use(bodyParser.urlencoded({ extended: true }));api.post('/secure', function(req, res) {    const token = jwt.sign({ user: { id: 1, name: 'ME!', role: 'average' } }, 'dsfklgj');    console.log(token);    res.json({ jwt: token });});api.post('/check/post', function(req, res) {    const token = req.body.jwt;    console.log('token: ' + token);    const x = jwt.verify(token, 'dsfklgj', function(err, decoded) {        if (err) throw err;        console.log(decoded);    });    console.log(x);    if (x != true) {        res.json({ auth: false });    } else {        res.json({ auth: true });    }});api.set('port', 3000);var server = http.createServer(api);server.listen(api.get('port'), function() {    console.log("Express server listening on port " + api.get('port'));});

BTW there is no way to test it like like this const x = jwt.verify(token, 'dsfklgj', function (err, decoded) {. Either write it in Sync way or check condition in async callback function. In your case, x will be undefined and no guarantee when it will run.