Home > Mobile >  Authenication with JWT returning empty array with a GET request [NodeJS]
Authenication with JWT returning empty array with a GET request [NodeJS]

Time:05-27

Trying to practice JWT with NodeJS but when I try to run a GET request using the headers of the Authorization: Bearer , it returns an array instead of the object with the token, I tried with the Postman app but to no avail

This is the code, the get and post request code:

    const express = require('express');
require('dotenv').config();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const app = express();

const user = [
    {
        username: 'John',
        email: '[email protected]'
    }, 
    {
        username: "Joshua",
        email: '[email protected]'
    }
]

app.use(express.json())

app.get('/api', authenicateToken, (req, res,) => {
    res.json(user.filter(post => post.username === req.body.name))
})

app.post('/login', (req, res) => {
    const username = req.body.username
    const use = { name: username }

    const accessToken = jwt.sign(use, process.env.ACCESS_KEY)
    res.json({ accessToken: accessToken })
})

function authenicateToken (req, res, next) {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]
    if(token === null) return res.sendStatus(403)

    jwt.verify(token, process.env.ACCESS_KEY, (err, user) => {
        if(err) return res.sendStatus(403)
        req.user = user
        next()
    })
}

app.listen(4000, () => {
    console.log('Can you hear me?');
})

enter image description here

CodePudding user response:

filter returns an array, use find method it returns single item.

res.json(user.find(post => post.username === req.body.name))
  • Related