UnhandledPromiseRejectionWarning, Express.js and Node.js - html

I am completely new to Node.js and Express.js and have been trying to work through some examples to integrate the Shippo API into my E-commerce web app but I'm getting some errors that I just can't solve despite reviewing my code several times.
I get the UnhandledPromiseRejectionWarning error, which, from I've read online, means that somewhere in my code there is something a .then() section which does not include a "catch" or a "what to-do" is the request returns an error. Any help would be greatly appreciated.
This is my code:
var express = require('express')
var app = express()
var http = require('http');
var Raven = require('raven');
var shippo = require('shippo')('ACCESS_TOKEN');
var engines = require('consolidate');
const bodyParser = require('body-parser');
const path = require('path');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.engine('html', engines.mustache);
app.set('view engine', 'html');
//app.use(express.static(path.join(_dirname,'/')));
app.get('/', function (req, res) {
res.render('Index.html');
})
app.post('/', function (req, res) {
var addressFrom = {
"object_purpose":"PURCHASE",
"name": "SENDER_NAME",
"company":"Shippo",
"street1":"215 Clayton St.",
"city":"San Francisco",
"state":"CA",
"zip":"94117",
"country":"US", //iso2 country code
"phone":"+1 555 341 9393",
"email":"SENDER_EMAIL",
};
// example address_to object dict
var addressTo = {
"object_purpose":"PURCHASE",
"name": req.body.fnames + ' ' + req.body.lnames,
"company": req.body.company,
"street1":req.body.street,
"city":req.body.city,
"state":req.body.state,
"zip":req.body.zipcode,
"country": req.body.country, //iso2 country code
"phone":"+1 555 341 9393",
"email":"support#goshippo.com",
};
// parcel object dict
var parcelOne = {
"length":"5",
"width":"5",
"height":"5",
"distance_unit":"in",
"weight":"2",
"mass_unit":"lb"
};
var shipment = {
"object_purpose": "PURCHASE",
"address_from": addressFrom,
"address_to": addressTo,
"parcels": [parcelOne],
"submission_type": "DROPOFF"
};
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
shippo.transaction.list({
"rate": transaction.rate
})
.then(function(mpsTransactions) {
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
}, function(err) {
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});
})
app.post('/successp', function (req, res) {
var token = req.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 1000,
currency: "eur",
description: "Example charge",
source: token,
}, function(err, charge) {
// asynchronously called
});
res.send('Thanks!')
})
app.post('/successp', function (req, res) {
var token = req.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 1000,
currency: "eur",
description: "Example charge",
source: token,
}, function(err, charge) {
// asynchronously called
});
res.send('Thanks!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
And this is the Error I get:
Example app listening on port 3000!
(node:2378) UnhandledPromiseRejectionWarning
(node:2378) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2378) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm also not completely sure about the purpose for some of the lines (again, i'm very new to express and node.js). What is engine and mustache? also, I see that this sample code uses APP.POST('/succesp', function(req, res)...), what exactly is that '/succesp'? Another html file I need to create? Also, what is that "app.use(express.statc([ath.join(_dirnam,'/')));" at the beginning?

You need to be a little careful using the format then(FN, errorFn), because if there's an error inside the then, the errorFn won't catch it. It's better to use then(fn).catch(errorFn). This will allow all errors in any then above to filter down to the last catch for handling.
For example, the first call properly catches the error, the second doesn't:
function fn() {
return Promise.resolve("good")
}
fn()
.then(r => {
throw ("whoops")
})
.catch(err => console.log(err)) //<-- catch works here
fn()
.then(r => {
throw ("whoops")
},
err => console.log(err) // this can't catch the error above; it will only catch rejections on fn()
)
It doesn't show in the snippet but if you look at the console, you'll see an unhandled rejection error.
In your code, you can flatten out the promise chain by returning the promise from shippo.transaction.list. Then you can add a catch at the end to handle errors.
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
return shippo.transaction.list({ // return this promise
"rate": transaction.rate
})
.then(function(mpsTransactions) { // so this can flatten out
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
.catch(function(err) { // catch errors
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});
})
Since this is hard to run locally without all the pieces, I'm not positive about the source of the error, but it looks like you are sending res.status(200).send() inside a loop, which might lead to an error if it gets called twice.

Without reading the full code, you shouldn't try to catch an error with a callback function when using Promises. You catch errors in Promises using a .catch block
And you should also return the first promise, so that it passes to the next .then function (if your intention is to return the shippo.transaction.list as mpsTransactions)
Something like this:
shippo.transaction.create({
"shipment": shipment,
"servicelevel_token": "ups_standard",
"carrier_account": 'CARRIER_TOKEN',
"label_file_type": "PDF"
})
.then(function(transaction) {
return shippo.transaction.list({
"rate": transaction.rate
})
})
.then(function(mpsTransactions) {
mpsTransactions.results.forEach(function(mpsTransaction){
if(mpsTransaction.object_status == "SUCCESS") {
console.log("Label URL: %s", mpsTransaction.label_url);
console.log("Tracking Number: %s", mpsTransaction.tracking_number);
console.log("E-Mail: %s", mpsTransaction.object_owner);
console.log(mpsTransaction.object_status);
res.status(200).send("Label can be found under: " + mpsTransaction.label_url);
} else {
// hanlde error transactions
console.log("Message: %s", mpsTransactions.messages);
}
});
})
.catch(function (error) {
// Deal with an error
console.log("There was an error creating transaction : %s", err.detail);
res.send("something happened :O")
});

Related

get real-time json data from twilio runtime with axios

I am trying to achieve real-time data from twilio server-less function. I am using a boilerplate function edited a little bit.What I want is json data in server and voice response in call consecutively .but the following code is not sending json data to server.
const axios = require('axios');
exports.handler = function (context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
twiml.say('you are welcome ');
const instance = axios.create({
baseURL: 'http://fafc4eac4162.ngrok.io/',
timeout: 3000,
});
instance
.post('/test', {
id: 1,
title: 'Twilio'
})
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
return callback(error);
});
return callback(null, twiml);
};
It shows below error,but it sends data successfully if I do not use the voice response callback return callback(null, twiml) and rather use simple return callback(null, response.data);
{"message":"timeout of 3000ms exceeded","name":"Error","stack":"Error: timeout of 3000ms
exceeded\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n
at RedirectableRequest.handleRequestTimeout
(/var/task/node_modules/axios/lib/adapters/http.js:280:16)\n at Object.onceWrapper
(events.js:286:20)\n at RedirectableRequest.emit (events.js:198:13)\n at
Timeout._onTimeout (/var/task/node_modules/follow-redirects/index.js:166:13)\n at
ontimeout (timers.j...
The return callback(null, twiml); should be in the .then block.
.then((response) => {
console.log(JSON.stringify(response.data));
return callback(null, twiml);
})
Also, the error indicates the 3000ms timeout is hit, is your application returning a 200-OK?

Ionic gives error undefined is not an object (evaluating '_co.user.username') when decoding the login user token

This is part of the error message that I am getting:
[Error] ERROR – TypeError: undefined is not an object (evaluating '_co.user.username') TypeError: undefined is not an object (evaluating '_co.user.username')(anonymous function)checkAndUpdateView — core.js:44...
My login process works fine and data of the user is gotten fine, on ionic serve version of my app, but on ios I can see that error message, like json encoding doesn't work fine or something. Why is the JSON working fine on website, but not on the app? Here is content of TokenService :
constructor(private cookieService: CookieService) {}
setToken(token) {
this.cookieService.set("chat_token", token);
}
getToken() {
return this.cookieService.get("chat_token");
}
deleteToken() {
this.cookieService.delete("chat_token");
}
getPayload() {
const token = this.getToken();
let payload;
if (token) {
payload = token.split(".")[1];
payload = JSON.parse(window.atob(payload));
}
return payload.data;
}
and this is the loginUser function in LoginComponent , that is triggered on logging in:
loginUser() {
this.showSpinner = true;
this.authService.loginUser(this.loginForm.value).subscribe(
data => {
this.tokenService.setToken(data.token);
localStorage.setItem("currentUser", JSON.stringify(data));
this.loginForm.reset();
setTimeout(() => {
this.router.navigate(["/streams"]);
}, 200);
},
err => {
this.showSpinner = false;
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}
Now, the server side, I have this rout in routes/ directory, in node express in file authRoutes.js:
router.post('/login', AuthCtrl.LoginUser);
And then I have this in routes/ directory, in file userRoutes.js:
const express = require('express');
const router = express.Router();
const UserCtrl = require('../controllers/users');
const AuthHelper = require('../Helpers/AuthHelper');
router.get('/users', AuthHelper.VerifyToken, UserCtrl.GetAllUsers);
router.get('/user/:id', AuthHelper.VerifyToken, UserCtrl.GetUser);
router.get(
'/username/:username',
AuthHelper.VerifyToken,
UserCtrl.GetUserByName
);
router.post('/user/view-profile', AuthHelper.VerifyToken, UserCtrl.ProfileView);
router.post(
'/change-password',
AuthHelper.VerifyToken,
UserCtrl.ChangePassword
);
module.exports = router;
This is the part of controller auth.js on node server side:
async LoginUser(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "No empty fields allowed" });
}
await User.findOne({ username: Helpers.firstUpper(req.body.username) })
.then(user => {
if (!user) {
return res.status(HttpStatus.NOT_FOUND).json({ message: "Username not found" });
}
return bcrypt.compare(req.body.password, user.password).then(result => {
if (!result) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Password is incorrect" });
}
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
return res.status(HttpStatus.OK).json({ message: "Login successful", user, token });
});
})
.catch(err => {
console.log("Error is:");
console.log(err);
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "Error occured" });
});
}
I resolved the issue by transferring all the stored data from CookieService, which is the main culprit of the error, to a localStorage. Just instead of storing payload and that cookie in CookieService, just transferred it to localStorage, and I didn't have any more problems. Seems like, the simpler - the better.

mysql connection rest service

Trying to make a simple rest service. The rest service is for pulling up a table from a local database. This rest service a want to make available for an android app.
Having trouble getting passed .then block. Tried catching the error but with no success. How do you catch the error if it's going wrong in the first .then
The below piece of code is the db.js, and sets up the connection to the database.
var sqlDb = require("mysql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new sqlDb.createConnection(settings.dbConfig);
conn.connect()
// !! Error unhandled
.then(function () {
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
};
After setting up connection the below piece of code is executed. With error handling.
var db = require("../core/db");
exports.getList = function (req, resp) {
db.executeSql("SELECT * FROM employees", function (data, err) {
if (err) {
// throws back error to web
resp.writeHead(500, "Internal Error", { "Content-Type":
"application/json" });
resp.write(JSON.stringify({ data: "ERROR occurred:" + err }));
} else {
resp.writeHead(200, { "Content-Type": "application/json" });
resp.write(JSON.stringify(data));
}
resp.end();
});
};
Made a separated js file for settings such as database. Tested my connection to the db on a same way. Excluded that problem but it keeps returning an error unhandled on the first .then. I'm not familiar with methods till now.
I think I found the problem. new sqlDb.Request(conn); The .Request is not available when using mysql. But how can I fix this
If you catch() an error it will not be caught again without returning a new rejection. Like this:
conn.connect()
.then(function () {
var req = new sqlDb.Request(conn);
// note the "return" here
return req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null, err);
// note the line below
return Promise.reject(err)
});
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
};
PS. Do you really need the callback(), why not use the Promise?

NodeJS Express MySQL post request throwing "Cannot set headers after they are sent to the client"

I try to send some MySQL results back via a express post request, but no matter what I try, there's always the following error:
(node:3743) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
at /home/dvs23/projects/Group/Visualizer/index.js:193:11
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:3743) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The important part of the code is:
app.post('/getNews', (req, res) => {
var prom = new Promise(function(resolve, reject) {
//create nodes for result
con.connect(function() {
console.log("Connected!");
con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
if (err) {
console.log(err);
reject(err);
return;
}
var nodesArr = [];
result.forEach((row) => {
nodesArr.push({
"id": row["ID"],
"size": row["length(Text)"]
});
});
con.query("SELECT * FROM newsSim;", function(err, result2, fields) {
if (err){
console.log(err);
reject(err);
return;
}
var linksArr = [];
result2.forEach((row) => {
linksArr.push({
"source": row["TID1"],
"target": row["TID2"],
"value": row["SIM"]
});
});
console.log({
"nodes": nodesArr,
"links": linksArr
});
resolve({
"nodes": nodesArr,
"links": linksArr
});
});
});
});
})
.then(function(result) {
console.log(result);
res.send(result); //send result to client
}, function(err) {
console.log("END"+err);
res.send({
"nodes": [],
"links": []
});
});
});
App is my express-app, the request comes from a static HTML page, which is also served by the NodeJS server, via jQuery.
I already use a promise, so how is it possible send is already called??
Also without promises, just nested queries, there's the same error (obviously without the UnhandledPromiseRejectionWarning stuff).
EDIT:
It's not a problem with the nested MySQL-queries, even the following does not work:
app.post('/getNews', (req, res) => {
//var text = req.fields["text"];
var prom = new Promise(function(resolve, reject) {
//create nodes for result
con.connect(function() {
console.log("Connected!");
con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
if (err) {
console.log(err);
reject(err);
return;
}
var nodesArr = [];
result.forEach((row) => {
nodesArr.push({
"id": row["ID"],
"size": row["length(Text)"]
});
});
resolve(nodesArr);
return;
});
});
})
.then(function(news) {
console.log(news);
//if (res.headersSent) return;
res.send(news); //send result to client
}, function(err) {
console.log("END"+err);
//if (res.headersSent) return;
res.send({
"nodes": [],
"links": []
});
});
});
If I use the if(res.headersSent), simply nothing is sent back to my site, neither an empty result, nor the real result, which is fetched as wanted -> I can log it to console...
EDIT2:
app.post('/getNews', (req, res) => {
//var text = req.fields["text"];
req.connection.setTimeout(6000000, function () {
console.log("Timeout 2");
res.status(500).end();
});
var prom = new Promise(function(resolve, reject) {
//create nodes for result
con.connect(function() {
console.log("Connected!");
con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
if (err) {
console.log(err);
reject(err);
return;
}
var nodesArr = [];
result.forEach((row) => {
nodesArr.push({
"id": row["ID"],
"size": row["length(Text)"]
});
});
con.query("SELECT * FROM newsSim;", function(err2, result2, fields2) {
if (err2){
console.log(err2);
reject(err2);
return;
}
var linksArr = [];
result2.forEach((row) => {
linksArr.push({
"source": row["TID1"],
"target": row["TID2"],
"value": row["SIM"]
});
});
resolve({
"nodes": nodesArr,
"links": linksArr
});
return;
});
});
});
})
.then(function(news) {
//if (res.headersSent) return;
res.send(news); //send result to client
console.log(news);
}, function(err) {
console.log("END"+err);
//if (res.headersSent) return;
res.send({
"nodes": [],
"links": []
});
});
});
Tried to set timeout, but Now the error occurs before the timeout callback is called...
(node:9926) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
at /home/dvs23/projects/Group/Visualizer/index.js:198:11
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:9926) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9926) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Timeout 2
Don't ask me why, but it seems to work now... Possibly setting a specific timeout as suggested by oniramarf was the key. Also added
multipleStatements: true
to mysql.createConnection(...) and moved static stuff to different path:
app.use('/site', express.static('static'));
but that's possibly not the reason it works now :)
Code:
app.post('/getNews', (req, res) => {
//var text = req.fields["text"];
var prom = new Promise(function(resolve, reject) {
//create nodes for result
con.connect(function() {
console.log("Connected!");
con.query("SELECT ID,length(Text) from news;", function(err, result, fields) { //SELECT ID,length(Text) FROM news;
if (err) {
console.log(err);
reject(err);
return;
}
con.query("SELECT * FROM newsSim;", function(err2, result2, fields2) {
if (err2) {
console.log(err2);
reject(err2);
return;
}
var imporIDs = new Set();
var linksArr = [];
result2.forEach((row) => {
if (row["SIM"] > 0.25) {
imporIDs.add(row["TID1"]);
imporIDs.add(row["TID2"]);
linksArr.push({
"source": row["TID1"],
"target": row["TID2"],
"value": row["SIM"]
});
}
});
var nodesArr = [];
result.forEach((row) => {
if (imporIDs.has(row["ID"])){
nodesArr.push({
"id": row["ID"],
"size": row["length(Text)"]
});
}
});
resolve({
"nodes": nodesArr,
"links": linksArr
});
return;
});
});
});
})
.then(function(news) {
//if (res.headersSent) return;
res.send(news); //send result to client
console.log(news);
}, function(err) {
console.log("END" + err);
//if (res.headersSent) return;
res.send({
"nodes": [],
"links": []
});
});
});
var server = http.createServer(app);
server.listen(8080, function() {
console.log('localhost:8080!');
});
server.timeout = 120000;
Edit:
Really seems to be the timeout, after some changes the error occurred again, so I set server.timeout = 12000000 and it worked again :)

How do I add routes before jsonwebtoken?

I'm working with jsonwebtoken and Im not entirely sure how it works. I have normal sign in sign up routes that should go before the .verify function. Ive used jwt many times but never had tried using routes before it.
Here is my routes files
var express = require('express');
var router = express.Router();
var usersController = require('../controllers').users;
var jwt = require('jsonwebtoken');
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
router.post('/signin', function(req,res,next) {
return usersController.signin(req,res);
});
router.post('/social-signin', function(req,res,next) {
return usersController.authSignin(req,res);
});
router.use('/auth', function (req,res,next) {
jwt.verify(req.query.token, 'secret', function (err, decoded) {
if (err) {
return res.status(401).json({
title: 'You are not authorized to do that',
error: "Please sign out and sign back in"
})
}
});
next();
});
router.get('/auth', function(req,res){
return usersController.getUser(req, res);
});
router.patch('/auth/update/:userId', function(req,res) {
return usersController.update(req,res);
});
router.delete('/auth/delete', function(req,res,next) {
return usersController.destroy(req,res);
});
module.exports = router;
Im receiving this error when doing a GET request for getUser.
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/user/auth?token=eyJhbGciOiJI…3Njd9.FE3sYhOSFhfhnxkACKSmclcHEWKVhpItuAMqBl-A-5w", ok: false, …}
error
:
{title: "You are not authorized to do that", error: "Please sign out and sign back in"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
I know its probably simple but I just have no idea.
*** Here is the code for getUser
getUser: function getUser(req, res) {
var decoded = jwt.decode(req.query.token);
return User.findOne({
where: {
id: decoded.user.id
}
}).then(function(user){
return res.status(200).json({
title: "User found",
obj: user
});
}).catch(function(error) {
return res.status(400).json({
title: 'There was an error getting user!',
error: error
});
});
},
In your auth, try:
router.use('/auth', function (req,res,next) {
jwt.verify(req.query.token, 'secret', function (err, decoded) {
if (err) {
return next(new Error('You are not authorized to do that'));
}
});
next();
});
This is still an issue
Since your getUser returns a Promise, and you are just returning that from your route. I believe you want to wait on the result of the Promise, before returning from your route.