Always returning 500 error - node.js

var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
From the front end I am sending a username and password. I am expecting to either be receiving errors 200 or 401. For some reason though I receiving error 500 which is the default error handler. I am not sure how it is coming here. On my server console Yes1 and Yes2 are being printed so why am I not getting error 401?

I don't know if you have more code or not, but you need to install your router with app.use('/', router).
You also need to install the body-parser middleware to be able to parse req.body.
Your whole application should look something like this:
// router.js
var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
console.log(req.body);
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
});
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
// server.js
var express = require('express');
var bodyParser = require('body-parser');
var customRouter = require('./router.js');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use('/', customRouter);
app.listen(3000, function () {
console.log('Listening on port 3000...');
});
See error handling and routing documentation.

It appears that your middleware handler is firing, because 401 is an error, and you are resetting the status to 500.

Related

Postman only showing error message and no request is working

Hi so I'm new in this domain and I'm working on some big project so here's the issue, i'm trying to run postman changing the requests from get to post etc but it's not working here's the app.js file
const express = require('express')
const cors = require("cors");
require("dotenv").config();
const con= require("./helpers/connection");
const bodyParser = require('body-parser');
const app = express()
const port = 3000
app.use(cors({ origin: '*' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// parse env variables
app.use(function(req, res, next) {
req.con = con
next()
})
app.use("/", require("./routes/routes"));
// Handling errors
//* Handling not mapped routes
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
//* Handling thrown or server errors
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
And this is my router file
const express = require("express")
const router = express.Router()
const userController = require("../../controllers/usersController.js")
router.get("/", userController.getUsers)
router.get("/:id", userController.getUserById)
router.post("/create", userController.create)
router.put("/:id", userController.edit)
router.delete("/:id", userController.delete)
module.exports = router
when i go to postman and try any of these request this is what i get
{
"error": {
"message": "Not found"
}
}
Please if anyone has any idea why it's not working do share with me

GET localhost:4200/api 404 (Not Found) after submit data

I download the https://github.com/SinghDigamber/Angular8MeanstackAngularMaterial
and deployed it.
But while I tried to save the data and review the data, i always get the
GET http://localhost:4200/api 404 (Not Found)
add data to db error picture
get data to db error picture
Angular v8.0.0
mongoDB v4.0.10
nodejs v12.2.0
//app.js
let express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
cors = require('cors'),
bodyParser = require('body-parser'),
dataBaseConfig = require('./database/db');
// Connecting mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(dataBaseConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database connected sucessfully ')
},
error => {
console.log('Could not connected to database : ' + error)
}
)
// Set up express js port
const studentRoute = require('./routes/student.route')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors());
// Setting up static directory
app.use(express.static(path.join(__dirname, 'dist/angular8-meanstack-angular-material')));
// RESTful API root
app.use('/api', studentRoute)
// PORT
const port = process.env.PORT || 8000;
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));
});
// Index Route
app.get('/', (req, res) => {
res.send('invaild endpoint');
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/angular8-meanstack-angular-material/index.html'));
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
I think you forgot to export get and post functions for your API routes.
you can create routes like this in studentRoute File.
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
return "Hello World";
})
router.post('/', function (req, res, next) {
return "Hello World";
})
module.exports = router;````

How to prevent response from server directly display in browser?

I am using express.js framework for my node.js server.
This is how I setup my server.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var createUsers = require('./routes/users/createUsers');
var updateUsers = require('./routes/users/updateUsers');
var deleteUsers = require('./routes/users/deleteUsers');
var readUsers = require('./routes/users/readUsers');
var app = express();
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();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'project'
});
res.locals.connection.connect();
next();
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/createUsers', createUsers);
app.use('/updateUsers', updateUsers);
app.use('/deleteUsers', deleteUsers);
app.use('/readUsers', readUsers);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.ejs');
});
var http = require('http');
module.exports = app;
var server = http.createServer(app);
server.listen(4000);
This is my readUsers.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
//console.log("pending data");
res.locals.connection.query('SELECT id,name,email,username,address,phone,status FROM user', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
});
});
module.exports = router;
My server is listen at port 4000. My react frontend componentDidMount() function use axios.get("http://localhost:4000/readUsers") to read the data from database and it worked well.
However, if I directly type in http://localhost:4000/readUsers in my browser, it will directly connect to my database and read all User data and displayed the data in browser. This is not I want because everyone can read my data if they know this address. Any way to prevent this issue?
Add middleware to your router. here's the doc Router-level middleware
Express have many middleware, one of it is route-level middleware. This middleware handle anything between users and your function.
Here is the example i fetch from the documentation.
var app = express()
var router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
In your case you may add some permission validation before request. Usually it's an API key, but it can be anything, secret word in header, secret parameter, everything.
Here is the example for your case.
function isPermitted(req, res, next) {
var permitted = false;
// Your validation here, is your user permitted with this access or not.
if (permitted) {
next();
} else {
res.send('Sorry, you are not belong here.');
}
}
/* GET home page. */
router.get('/', isPermitted, function(req, res, next) {
//console.log("pending data");
res.locals.connection.query('SELECT id,name,email,username,address,phone,status FROM user', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
});
});
Use POST instead of GET as method for request.

post using restler and node.js is not returning

I am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");

Express JS 4 sends console.log output

This is very strange in that Express JS is sending the console.log output to the client without res.send being used.
Calling the /api POST endpoint shows the "Hello" from the parseJSON back to the client.
How can I get this to stop?
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next(err);
});
// handling 404 errors
app.use(function(err, req, res, next) {
if (err.status !== 404) {
return next();
}
res.send(err.message || '** 404 error **');
});
app.post('/api', function(req, res) {
parseJSON(req.body);
res.status(200).end();
});
app.listen(80);
function parseJSON(jsonData)
{
console.log("HELLO");
}

Resources