How to send JWT token to node.js server
I think the problem here is that you are getting an empty object in req.body when you try to pass it as a json string in postman. I would recommend either
- pass your credentials in x-www-form-urlencoded tag in postman or
- Using express.Router() and creating different files for routes
In your index.js file write:
app.use('/', require('./routes.js'))
And create a file with name routes.js and put your routes as this:
const express = require('express');const router = express.Router();router.post('/', (req, res) => { let username = req.body.username; let password = req.body.password;console.log(req.body); if (username !== process.env.USER_NAME && password !== process.env.USER_PASSWORD) { res.json('Invalid credentials'); } else { const token = jwt.sign({ username: username }, process.env.SECRET_KEY, { expiresIn: 3600 }); return res.send({token}); }});module.exports = router;