404 Not found node - javascript

Hi so I have been using this node server for some time and it recently stopped working (presumably due to some logical error I mistakenly adjusted), throwing a 404 when I run the server. When I call on it with an http request it throws a 404 as well and shows the same on load from the actual URL in a browser. What is going on?
ter image description here]3]3
index.js:
//Environment Vars
var uri = process.env.NODE_ENV || "development"
console.log(uri + " environment")
//Express App
var express = require('express');
var app = express();
//Api for reading http post request body in express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
//Log Connections
app.use(function timeLog (req, res, next) {
console.log('incoming connection . . . ')
console.log(req)
next()
})
//API middelware
var api = require('./api')
app.use('/api', api)
app.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'Welcome!', success: true, error: null }));
});
//Create Server
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
console.log('Server running on port ' + port + '.');
});
api.js
var express = require('express')
var router = express.Router()
var stripe_key = process.env.STRIPE_KEY || "sk_test_P9XQtrrfGYU9mF8h6C47bgUp"
var stripe = require('stripe')(stripe_key);
var request = require("request-promise-native")
//API
router.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'API Gateway', success: true, error: null }));
}) // Just for testing, just for error-handling
//1. Create a customer account
router.post('/new_customer', function (req, res) {
console.log("Creating new customer account...")
var body = req.body
stripe.customers.create({ email: body.email, })
.then((customer) => {
console.log(customer)
// Send customerId -> Save this on Firebase for later use
res.status(200).send(JSON.stringify({ success: true, error: null, customerId: customer.id }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//2. Save Credit Card with token
router.post('/new_card', function (req, res) {
var customerId = req.body.customerId
var token = req.body.token
stripe.customers.update(customerId, { source: token })
.then((customer) => {
console.log(customer)
res.status(200).send(JSON.stringify({ success: true, error: null }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//3. Use customerId to post a charge
router.post('/new_charge', function (req, res) {
var customerId = req.body.customerId
var amount = req.body.amount
var source = req.body.source
stripe.charges.create({
amount: amount, //in cents
currency: "usd",
customer: customerId, //CUSTOMER_STRIPE_ACCOUNT_ID
source: source, // obtained with Stripe.js
}).then((charge) => {
res.status(200).send(JSON.stringify({ message: 'Sucess.', success: true, error: null }));
}).catch((error) =>{
res.status(400).send(JSON.stringify({ message: 'Error', success: false, error: error }));
})
})
router.post('/ephemeral_keys', (req, res) => {
const stripe_version = req.body.api_version;
var customerId = req.body.customerId;
if (!stripe_version) {
res.status(400).end();
return;
}
console.log(stripe_version)
// This function assumes that some previous middleware has determined the
// correct customerId for the session and saved it on the request object.
stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: stripe_version}
).then((key) => {
console.log("Ephemeral key: " + key)
res.status(200).json(key);
res.status(200).send(JSON.stringify({ message: 'AAAAhh', success: true, error: null }));
}).catch((err) => {
console.log("Ephemeral key error: " + err)
res.status(200).send(JSON.stringify({ message: 'ABBBBBB', success: true, error: null }));
res.status(500).end();
});
});
module.exports = router;
Other details:
Two important files: index.js & api.js but functionality is all in api.js which is why URL stem goes: .../api/...

Ok got the issue and its as silly as it can get. Are you sure you started the right server ? Its definitely not the node server. Its the http-server you have started. To start the server through node you need to go into the directory (in the terminal) and write "node index.js". Necessary code to start a http-server is written inside index.js.
Got this from the below screenshot.

the error for me is that you are making a GET request on a route that requires a POST request:
router.post('/new_charge', function (req, res) {
...
})
So you should check that you are making a post request to this route and not a GET request. How are you accessing that route from the client?

There is no router.get route for '/api/new_charge', there is one router.post route though.

Where is your router.get('/new_charge') route? it's not in the files you posted. You might have either deleted it or the /new_charge route needs to be used as post and not get.

Related

Connection refused by mongo server idk why

I have a mongo model like this:-
var mongoose = require('mongoose');
const itemsModel = new mongoose.Schema({
_id: {
type: String,
},
userName: {
type: String,
required: true
},
description: {
type: String,
required: false
},
itemId: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model("itemsModel", itemsModel);
and I am handling my backend route in a file called itemRoute.js like this:-
const express = require("express");
const router = express.Router();
const id = require('uuid');
const itemsModel = require("../src/model/itemsModel");
router.post('/add-item/', (req, res) => {
const { userName, description, itemId } = req.body;
itemsModel.findOne({
itemId: itemId,
userName: userName,
}, (error, prevData) => {
if(error){
return res.send({
success: false,
description: `Internal Server Error ${error}`
});
}
if (prevData.length > 0){
itemsModel.findOneAndUpdate(
{ _id: prevData[0]._id },
{ description: description },
(error, status) => {
if (error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
} else {
return res.status(200).json({
success: true,
description: "Updated item successfully",
prevData: prevData,
status: status
});
}
}
);
}
const newModel = new itemsModel;
newModel._id = id.v4();
newModel.userName = userName;
newModel.itemId = itemId;
newModel.description = description;
newModel.save((error, user) => {
if(error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
}
return res.status(200).json({
success: true,
description: "Added item to db",
user: user
});
});
});
});
router.get('/get-items/:itemId/', (req, res) => {
console.log(req.body);
const itemId = req.params.itemId;
return res.status(200).json({
success: true,
description: "Nicee",
id: itemId,
});
});
module.exports = router;```
I have the following in my index.js express file:-
app.use('/api', require('./routes/itemRoute'));
and I am calling from my frontend like this:-
handleAddItemButton = (event) => {
event.preventDefault();
const data = {
userName: this.props.userName,
description: this.state.description,
itemId: this.props.itemId,
}
fetch(`http://localhost:8000/api/add-item/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch((err) => console.log(err));
};
My index.js file:-
/* jshint esversion:6 */
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('./build'));
app.use(express.static('./build/static'));
app.use('/api', require('./routes/auth'));
app.use('/api', require('./routes/items'));
app.use('/api', require('./routes/itemRoute'));
mongoose.set('useCreateIndex', true);
const port = 8000
mongoose.connect('mongodb://localhost:27017/item-app', {
useNewUrlParser: true
})
app.get('/*', (req, res) => {
res.sendFile(path.resolve('./build/index.html'))
})
app.listen(port, () => console.log(`server running at ${port}`));
When my frontend actually makes the request, I am thrown the following error:-
POST http://localhost:8000/api/add-item/ net::ERR_CONNECTION_REFUSED
I have looked through my code again and again but to no avail. Any and all help is sincerely appreciated. Please guide me through what Im doing wrong.
Edit 1:-
After #ewokx comment I ran mongod and got the following;-
Is this the issue? How to solve this?
MongoDB requires a data folder to store its files.
The default location for the MongoDB data directory is c:\data\db. So, create this folder it will solve your issue.
Hi so I seem to have successfully solved the problem. The problem wasn't with any of the things like db permissions, mongod, ports or something like that. I reset my index.js file to match the db name in the db connection.
Another thing I was doing wrong, I was passing a json stringified object as the request body. Removing that and on connecting proeprly to the db, the code started working nicely.

Stripe & Node.js - "Cannot POST /create-checkout-session"

I'm trying to follow the Stripe Checkout subscription instructions:
https://stripe.com/docs/billing/subscriptions/build-subscriptions?ui=checkout
When I submit the form, over localhost I get "Cannot POST /create-checkout-session" (404 in network tab), and if I run from my production server, it just opens /create-checkout-session as a new (blank) Vue page. I have tried changing the form action to https://mydomain.xyz/create-checkout-session, but it didn't work.
Subscribe.vue
<form action="/create-checkout-session" method="POST">
<input type="hidden" name="priceId" value="[removed for Stack Overflow]" />
<button type="submit">Checkout</button>
</form>
I don't know if something is interfering with the endpoint, so I've copied my entire app.js file:
app.js
let express = require('express'),
cors = require('cors'),
mongoose = require('mongoose'),
database = require('./database'),
bodyParser = require('body-parser');
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = require('stripe')('[removed for StackOverflow]');
//connect mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(database.db, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Database connected")
},
error => {
console.log("Database couldn't be connected to: " + error);
}
)
const cryptoEndPoint = require('../backend/routes/crypto.route')
const app = express();
app.use(decodeIDToken);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors())
//API
app.use('/api', cryptoEndPoint)
app.post("/create-checkout-session", async (req, res) => {
console.log("can't even get anything to console log, only get createError is not defined");
const { priceId } = req.body;
// Create new Checkout Session for the order
// Other optional params include:
// [billing_address_collection] - to display billing address details on the page
// [customer] - if you have an existing Stripe Customer ID
// [customer_email] - lets you prefill the email input in the form
// [automatic_tax] - to automatically calculate sales tax, VAT and GST in the checkout page
// For full details see https://stripe.com/docs/api/checkout/sessions/create
try {
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [
{
price: priceId,
// For metered billing, do not pass quantity
quantity: 1,
},
],
// {CHECKOUT_SESSION_ID} is a string literal; do not change it!
// the actual Session ID is returned in the query parameter when your customer
// is redirected to the success page.
success_url: 'https://mydomain.xyz/thankyou?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'https://mydomain.xyz/thankyou',
});
return res.redirect(303, session.url);
} catch (e) {
res.status(400);
return res.send({
error: {
message: e.message,
}
});
}
});
//create port
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port);
})
//Find 404
app.use((req, res, next) => {
next(createError(404));
})
//error handler
app.use(function (err, req, res, next) {
console.log(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
})
/**
* Decodes the JSON Web Token sent via the frontend app
* Makes the currentUser (firebase) data available on the body.
*/
async function decodeIDToken(req, res, next) {
if (req.headers?.authorization?.startsWith('Bearer ')) {
const idToken = req.headers.authorization.split('Bearer ')[1];
// console.log(idToken);
try {
const decodedToken = await admin.auth().verifyIdToken(idToken);
// console.log("one");
req['currentUser'] = decodedToken;
// console.log("two");
} catch (err) {
console.log("error: " + err);
}
}
next();
}
app.post("/webhook", async (req, res) => {
let data;
let eventType;
// Check if webhook signing is configured.
const webhookSecret = '[removed for Stack Overflow]'
if (webhookSecret) {
// Retrieve the event by verifying the signature using the raw body and secret.
let event;
let signature = req.headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
webhookSecret
);
} catch (err) {
console.log(`⚠️ Webhook signature verification failed.`);
return res.sendStatus(400);
}
// Extract the object from the event.
data = event.data;
eventType = event.type;
} else {
// Webhook signing is recommended, but if the secret is not configured in `config.js`,
// retrieve the event data directly from the request body.
data = req.body.data;
eventType = req.body.type;
}
switch (eventType) {
case 'checkout.session.completed':
//...
break;
case 'invoice.paid':
//...
break;
case 'invoice.payment_failed':
//...
break;
default:
// Unhandled event type
}
res.sendStatus(200);
});
Does anyone know what is going wrong?
I added this to my app.js file, and it's working:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(allowCrossDomain);

I don't know why my get request sometimes works but sometimes doesn't (404 not found)

I'm currently learning angular and working on a project with a mongoDB database and express for my APIs. I want to fetch the comments of a post by the post ID,
The get request returns me a list of comments. the problem is when I first run node js the get request doesn't work, it only works when I first post a new comment and then run the get request for the comments again.
And as long as node is running the get request will continue to work whenever it's called for, until I restart node once again for the error to happen again.
it returns a 404 not found error.
This error doesn't happen with any other route, but my code is the same in all of them.
PS : I Have made sure that the function is getting the post id before the get request is made.
this is my server.js file
let express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
cors = require('cors'),
bodyParser = require('body-parser'),
dbConfig = require('./database/db');
//create Error definition
const createError = require('http-errors');
// Connecting with mongo db
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database sucessfully connected')
},
error => {
console.log('Database could not connected: ' + error)
}
)
const userRoute = require('./routes/user.route');
const postRoute = require('./routes/post.route');
const galleryRoute = require('./routes/Gallery.route');
const likeRoute = require('./routes/Like.Route');
const commentRoute = require('./routes/Comment.route');
const shareRoute = require('./routes/Share.route');
const profilePicRoute = require('./routes/ProfilePic.route');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.use(express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
app.use('/', express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
app.use('/api/users', userRoute);
app.use('/api/posts', postRoute);
app.use('/api/likes', likeRoute);
app.use('/api/profilePics', profilePicRoute);
app.use('/api/comments', commentRoute);
app.use('/api/shares', shareRoute);
app.use('/api/gallery', galleryRoute);
// Create port
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port)
})
// Find 404 and hand over to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message); // Log error message in our server's console
if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
res.status(err.statusCode).send(err.message); // All HTTP requests must have a response, so let's send back an error with its status code and message
});
this is my commentRoute.js
const express = require('express');
const commentRoute = express.Router();
// Comment model
let Comment = require('../models/Comment');
const createError = require('http-errors');
//multer for pic upload
const uploadMedia = require('../middleware/picUpload')
// Add Comment
commentRoute.route('/create').post((req, res, next) => {
// if(req?.files[0]){
// newComment.media = req?.files[0]
// }
let newComment = req.body;
newComment.creationDate = new Date(req.body.creationDate)
console.log(newComment)
Comment.create(newComment, (error, data) => {
// if (error instanceof multer.MulterError ) {
// error.message += "\nmulter Error";
// return next(error)
// }else
if (error){
return next(error)
}
else {
res.json(data);
}
})
//Get comments by parent ID
commentRoute.route('/read/byParentId/:idParent').get( async (req, res, next) => {
await Comment.find({idParent : req.params.idParent}, (error, data) => {
if(error){
return next(error)
}else{
res.json(data)
}
})
})
})
module.exports = commentRoute;
this is my mongoose comment schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema
let Comment = new Schema({
idUser: {
type : String
},
idParent : {
type : String
},
text : {
type : String
},
media : {
fieldname : { type : String },
originalname : { type : String },
encoding : { type : String },
mimetype : { type : String },
buffer : { type : Buffer },
},
creationDate : {
type : Date
}
},
{
collection: 'comments'
})
module.exports = mongoose.model('Comment', Comment);
this is my client side http get request
baseUrl = 'http://localhost:4000/api/comments';
headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http : HttpClient) { }
getCommentsByParentId(idParent : any){
return this.http.get(`${this.baseUrl}/read/byParentId/${idParent}`);
}
this is how I consume the api in the client side
getComments(){
this.commentService.getCommentsByParentId(this.idPost).subscribe({
next : (res : any) => {
this.comments = res
this.commentsCount = res.length
},
error : (err : any) => {
console.log("error getting comment list for post "+this.idPost)
}
})
}
client side error :
server side error :
thank you.
Edit :
post without the list of comments before I post a new comment
post after I post a new comment
Well, that's very obvious that the server can't find the entity in the DB.
You need to check one of the following:
Maybe when you restart the node server, you restart the db too. that can happen if you're using docker-compose locally. then when you run your node server again your DB starts but there's no data in the DB, therefore the service can't find any data.
After service restart you're using non-existing ID because of wrong UI flow.
I would guess that you're facing the first option.

Axios data is breaking the request

I have an express API and a ReactJs front-end. I try to make a POST call from my front-end directly to the local API.
For this I'm using axios.
The request is working fine when I set the parameters directly inside the query string but is always getting on timeout if I try to add the parameters through the data attribute of the axios.post() method.
Working
axios.post(`http://localhost:5001/site/authenticate?username=demo&password=demo`)
Not working
const payload = {
"username":"mh",
"password":"mh"
}
axios.post(`http://localhost:5001/site/authenticate`, payload)
My express server:
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var cors = require('cors');
const app = express();
const port = process.env.API_PORT || 5001;
app.use(cors());
app.set('secret', process.env.API_SECRET);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use((req, res, next) => {
let data = '';
req.setEncoding('utf8');
req.on('data', (chunk) => {
data += chunk;
});
req.on('end', () => {
req.rawBody = data;
next();
});
});
// Allow CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// SITE ROUTES -------------------
const siteRoutes = express.Router();
siteRoutes.post('/authenticate', function(req, res) {
console.log('auth');
getDocument(usersBucket, req.query.username)
.then((doc) => {
console.log("Authentification... TODO");
// return the information including token as JSON
res.json({
success: true,
status: 200,
token: token
});
})
.catch(() => {
res.status(401).json({ success: false, message: 'Authentification failed. User not found.' });
});
});
// route middleware to verify a token
siteRoutes.use(function(req, res, next) {
const token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('secret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.', status: 401 });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
siteRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome!' });
});
app.use('/site', siteRoutes);
app.listen(port, () => {
logger.log(`Express server listening on port ${port}`);
});
Any idea? Thanks.
Update
I replaced my route just to see if I got in or not (without worrying about parameters):
siteRoutes.post('/authenticate', function(req, res) {
console.log("go in");
res.json({
success: true,
status: 200,
});
});
But my console.log is not showing hen I use the payload (it is when I do not).
You should access the payload data via request.body, not the request.query:
// SITE ROUTES -------------------
const siteRoutes = express.Router();
siteRoutes.post('/authenticate', function(req, res) {
console.log('auth');
getDocument(usersBucket, req.body.username) // <------- HERE
.then((doc) => {
console.log("Authentification... TODO");
// return the information including token as JSON
res.json({
success: true,
status: 200,
token: token
});
})
.catch(() => {
res.status(401).json({ success: false, message: 'Authentification failed. User not found.' });
});
});
request.query are the parameters passed in the URL, like:
protocol://hostname:port/path/to.route?query_param_0=value_0&query_param_1=value_1
on your express endpoint request.query will be:
{
query_param_0: value_0,
query_param_1: value_1
}
while sending the payload, with the second argument in axios.post(url, payload):
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
on your express endpoint request.body will be:
{
firstName: 'Fred',
lastName: 'Flintstone'
}
when you use app.use(bodyParser.json()); (and you do).
You are using “getDocument(usersBucket, req.query.username)”
This means you express route is expecting username as a request param. That’s why it’s working when you use “?username=xx”
Instead try to get it from json body of request.
“req.body.username”
Also you should consider validating the request body or param as required.

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

I'm building my first SPA project with Vue.
I decided to go with NodeJS for the back-end, however, I'm having a headache building the login function with the JsonWebToken.
I had wrote some codes to see how JWT works and when I tried to see how JWT gets verified, server gave me an error.
JsonWebTokenError: jwt must be provided
at Object.module.exports [as verify] (c:\dir\node_modules\jsonwebtoken\verify.js:39:17)
at c:\projects\practice\demo\back\server.js:34:17
Below is the code for my server.js
This is the code for importing the stuff.
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const api = express();
api.use(bodyParser.json());
api.use(bodyParser.urlencoded({ extended: true }));
This is for the API for issuing JWT.
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});
});
This is the API for checking JWT.
api.post('/check/post', function (req, res) {
const token = req.body.jwt;
const x = jwt.verify(token, 'dsfklgj', function (err, decoded) {
if (err) throw err;
console.log(decoded);
});
if (x != true) {
res.json({ auth: false });
}else {
res.json({ auth: true });
}
});
jwt must be provided
This error happens when the coming token is null or empty.
Make sure that the Authorization header has a value of Bearer <Access Token>. Bearer < white space > < Access Token >
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.

Categories