nodejs custom error response does not take code error argument - node.js

I'm workin with a custom error response that I found in a tutorial. it's working correctly in all the node server, but in a specifies line it doesn't take the argument that specified the error code. It should return a 401 error but instead is returning me a 500 error code.
errorResponse.js
class ErrorResponse extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
module.exports = ErrorResponse;
The next is the porcion of code that doesn't working well.
auth.js
return next(new ErrorResponse('Unauthorized', 401))
If I use this aproach the error code is the correct.
return res.status(401).json('Unauthorized')
Edited and share server.js
require('dotenv').config({path: './config.env'});
const express = require('express');
const connectDB = require('./config/db');
const errorHandler = require('./middlewares/error');
connectDB();
const app = express();
app.use(express.json());
app.use('/api/auth', require('./routes/auth'));
app.use('/api/private', require('./routes/private'));
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => console.log('server on port', PORT));
process.on("unhandledRejection", (err, promise) => {
console.log(`logged Error: ${err}`)
server.close(() => process.exit(1))
});
app.use(errorHandler);
error.js
const errorHandler = (err, req, res, next) =>{
let error = { ...err };
error.message = err.message
if(err.code === 11000) {
const message = `Error de duplicaciĆ³n`;
error = new ErrorResponse(message, 400)
}
if(err.name === "ValidationError") {
const message = Object.values(err.errors).map((val) => val.message);
err = new ErrorResponse(message, 400)
}
res.status(error.status || 500 ).json({
succes: false,
error: error.message || "Error del servidor"
})
}

Related

Getting an error message n is not a function

I am writing a serverless netlify function when I hit /:uid endpoint, it shows me this error message n is not a function but when I hit / endpoint, it doesn't throw an error.
Please help me with this.
src/api.js file code
const express = require("express");
const cors = require("cors");
const fetch = require("node-fetch");
const helmet = require("helmet");
const serverless = require("serverless-http");
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const app = express();
const router = express.Router();
app.use(cors());
app.use(helmet());
const fetchWithToken = (endpoint, method = "GET") => {
return fetch(`${process.env.API_BASE_URL}${endpoint}`, {
method,
headers: {
Authorization: `token ${process.env.TOKEN}`,
},
});
};
router.get("/", (req, res) => {
res.send("JDKJKFJ");
});
router.get("/:uid", async (req, res) => {
try {
const data = await fetchWithToken(`/${req.params.uid}`, "GET");
res.status(200).json(data);
} catch (error) {
console.log(error.message);
res.status(500).json({ error });
}
});
app.use("/.netlify/functions/api", router);
module.exports.handler = serverless(app);
error message
TypeError: n is not a function
at /Users/rishipurwar/codingspace-proxy-server/functions/api.js:159:3133
at /Users/rishipurwar/codingspace-proxy-server/functions/api.js:159:3232
at o.handle_request (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:120:783)
at o (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:113:879)
at d.dispatch (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:113:901)
at o.handle_request (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:120:783)
at /Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:2533
at f (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:3502)
at f (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:3696)
at Function.v.process_params (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:3839)
at g (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:2476)
at Function.v.handle (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:3340)
at p (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:238)
at o.handle_request (/Users/rishipurwar/codingspace-proxy-server/functions/api.js:120:783)
at /Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:2905
at /Users/rishipurwar/codingspace-proxy-server/functions/api.js:106:2927
Response with status 500 in 57 ms.
You need to add .json() to the returned value from fetch:
try {
let data = await fetchWithToken(`/${req.params.uid}`, "GET");
data = await data.json()
res.status(200).json(data);
} catch (error) {
console.log(error.message);
res.status(500).json({ error });
}

Node.js DELETE Request return wrong response

I'm making a DELETE request on my nodejs server, but the response is wrong.
When i try to send a DELETE request at my localhost server, it returns success: 0, message: "Record Not Found"
but when i go to check in the database, the parameters are gone
index.js
require("dotenv").config();
const express = require("express");
const app = express();
const userRouter = require("./api/users/user.router");
var cors = require('cors');
var corsOptions = {
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use("/api/", userRouter);
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log("server up and running on PORT :", port);
});
user.router.js
const router = require("express").Router();
const {
deleteUtenti
} = require("./user.controller");
router.delete("/", deleteUtenti);
module.exports = router;
user.controller.js
const {
deleteUtenti
} = require("./user.service");
module.exports = {
deleteUtenti: (req, res) => {
const data = req.body;
deleteUtenti(data, (err, results) => {
if (err) {
console.log(err);
return;
}
if (!results) {
return res.json({
success: 0,
message: "Record Not Found"
});
}
return res.json({
success: 1,
message: "user deleted successfully"
});
});
}
};
user.service.js
const pool = require("../../config/database");
module.exports = {
deleteUtenti: (data, callBack) => {
pool.query(
`delete from utenti where email = ?`,
[data.email],
(error, results, fields) => {
if (error) {
callBack(error);
}
return callBack(null, results[0]);
}
);
}
};
is it a problem of the code or of the server?
A few days ago the same thing happened to me with another function but to solve it was enough to recreate the table in the database, I tried to do the same thing but it didn't work
I Just found the problem, results[0] on user.service.js did not read the response from the database, so to do some tests I changed it to results where all the response from the database came out and I saw that I just had to take the affectedRows response from the database, so I changed it to results.affectedRows and now everything works as it should.

"return next()" in node.js express throws "next is not defined" error

I'm working on a node.js application.
In my application the requests are going through a middleware which checks if the user is authenticated. In my middleware file though, I keep getting the "next is not defined" error back in my client. What might be the issue? I'm adding the App.js and the middleware file in here:
App.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { sequelize } = require('./models');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');
const auth = require('./middleware/auth');
// return instance of the app
app = express();
// setting up the cors config
app.use(cors({
origin: '*'
}));
// tell the app to parse the body of the request
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// tell the app to go through the middleware before proceeding to graphql
app.use(auth);
// setting the graphql route
app.use('/graphql', graphqlHttp({
schema: graphqlSchema,
rootValue: graphqlResolver,
graphiql: true,
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const message = err.message || 'An error occurred.';
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
}
})
);
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
res.status(status).json({ message: message, data: data });
});
sequelize.sync({ force: true })
.then(() => {
app.listen(8080);
})
.catch(err => {
console.log(err);
});
the auth.js file (the middleware):
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
const authHeader = req.get('Authorization');
if (!authHeader) {
req.isAuth = false;
return next();
}
const token = authHeader.split(' ')[1];
let decodedToken;
try {
decodedToken = jwt.verify(token, 'somesupersecretsecret');
} catch (err) {
req.isAuth = false;
return next();
}
if (!decodedToken) {
req.isAuth = false;
return next();
}
req.userId = decodedToken.userId;
req.isAuth = true;
next();
};

Node Express JWT invalid token

Working locally but when running prod build, I get the 401 error. Not sure what I am missing. I am having {message: "Invalid Token"} whenever I tried to make a call to any api within the app.
Server.js
require('rootpath')();
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('./_helpers/Jwt');
const errorHandler = require('_helpers/Error-handler');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
// use JWT auth to secure the api
app.use(jwt());
// api routes
app.use('/users', require('./users'));
// global error handler
app.use(errorHandler);
// start server
const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000;
if (process.env.NODE_ENV === 'production') {
app.use(express.static('../portal/dist'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'portal', 'dist', 'index.html'))
})
}
const server = app.listen(port, function () {
console.log('Server listening on port ' + port);
});
JWT.js
const expressJwt = require('express-jwt');
const config = require('../config.json');
const userService = require('../users/user.service');
module.exports = jwt;
function jwt() {
const secret = app.set('JWT_TOKEN', (process.env.JWT_TOKEN)) ;
return expressJwt({ secret }).unless({
path: [
// public routes that don't require authentication
'/users/authenticate',
'/users/register'
]
});
}
async function isRevoked(req, payload, done) {
const user = await userService.getById(payload.sub);
// revoke token if user no longer exists
if (!user) {
return done(null, true);
}
done();
};
Error handler.js
module.exports = errorHandler;
function errorHandler(err, req, res, next) {
if (typeof (err) === 'string') {
// custom application error
return res.status(400).json({ message: err });
}
if (err.name === 'ValidationError') {
// mongoose validation error
return res.status(400).json({ message: err.message });
}
if (err.name === 'UnauthorizedError') {
// jwt authentication error
return res.status(401).json({ message: 'Invalid Token' });
}
// default to 500 server error
return res.status(500).json({ message: err.message });
}
config.js
{
"secret": "Gu_*s+dF]x$E~n2B:#FwS.&Y;#M:sLMQ"
}
Added the interceptor into the app module. Not sure if I am missing something.
You need to provide isRevoked to the jwt instance
return expressJwt({ secret, isRevoked })

How do i test index.js for nodejs with env param?

I have the following index.js for my node js. When i run my coverage, it is telling me that else path is not taken for this line: if(enableCompression) {.
My .env is setting process.env.ENABLE_COMPRESSION = 'true' by default.
How do I test that path? I tried setting process.env.ENABLE_COMPRESSION = 'false' in my test case but it does not rerun the index.js again as the server is already started.
How do i go about doing it? I am using sinon for my unit test.
index.js:
require('dotenv').config({ path: require('find-config')('.env') });
const PORT = process.env.PORT;
const ENABLE_COMPRESSION = process.env.ENABLE_COMPRESSION;
let express = require('express');
let compression = require('compression');
//logging
let log4js = require('log4js');
log4js.configure('./config/log4js.json');
//Please do not remove this line, since CLI uses this line as guidance to import new controllers
let app = express();
let enableCompression = ENABLE_COMPRESSION === "true";
if(enableCompression) {
app.use(compression());
}
app.use(log4js.connectLogger(log4js.getLogger("app"), { level: 'auto' }));
let log = log4js.getLogger("api-app");
//importing route
let routes = require('./api/rest/apiRest');
//register the route
routes(app);
//reached here throw error 404, means no routes to handle inc. request
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
});
// catch errors
app.use((error, req, res, next) => {
log.error("ERROR - " + req.url + " - " + error.message);
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
//start application
module.exports = app.listen(PORT, () => {
log.info('API server started on: ' + PORT);
});

Resources