In my app.js I do this
app.use(function(req, res, next){
if(!req.user){
return res.redirect('/login_');
}
next();
})
I don't see anything wrong and in route/index.js I do
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
But I got an error. I know this is caused by the request is not ended but what's wrong with my code above? clueless with this error.
Full code of route/index.js
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
}
})
var upload = multer({ storage: storage })
var Photo = require('../models/photos');
router.get('/', function(req, res, next) {
if(req.user){
res.redirect('/'+req.user.username+'/screen');
}else{
res.redirect('/login_');
}
});
router.get('/:username/screen', function(req, res, next) {
res.render('screen', { user : req.user });
});
router.get('/:username', function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
res.render('upload_photo');
}
});
router.post('/:username', upload.any(), function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
var photo = new Photo({
photo:req.files[0].filename,
caption:req.body.caption
});
photo.save(photo);
res.sendStatus(200);
}
});
router.get('/:username/manager', function(req, res, next) {
Photo.getAllPhotos(function(err,result){
var headers = req.headers.host;
var pathname = '128.199.128.108:3000';
if(headers.indexOf('localhost') > -1){
pathname = 'localhost:3000'
}
res.render('manager',{pathname:pathname,photos:result});
});
});
//* passport for register/login_ *//
router.get('/register_', function(req, res) {
res.render('register', { });
});
router.post('/register_', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
router.post('/login_', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout_', function(req, res) {
req.logout();
res.redirect('/login_');
});
module.exports = router;
You are printing something before this line.
Either trace that, or instruct your server to cache some of the output to the user.
(if the server does not display anything to the user, headers can be sent, even if code tries to print something before)
However that is general knowledge, not familiar with node.js
Related
I'm having a small problem here. I want to display 404 not found if I input a wrong route.
The code below only shows 404 not found if I go to http://localhost:3000/
but when I enter http://localhost:3000/wrongroute it displays Cannot GET /wrongroute instead of
404 not found.
const bodyParser = require("body-parser");
const mysql = require('mysql');
const router = express.Router();
const db = mysql.createConnection({
host: 'xxx.xx.xx.xx',
user: 'root',
password: '12345',
database: 'test'
});
db.connect((err) =>{
if(err){
throw err;
}
console.log('Mysql Connected');
// res.send("Mysql Connected");
});
router.post('/login', function (req, res) {
res.send("This is from login route");
res.end();
})
router.post('/signup', function (req, res) {
res.send("This is from signup route");
res.end();
})
router.get('/', function(req, res){
res.send("404 not found");
});
module.exports = router;
Add this route at the END.
router.get("*", (_, res) => res.status(404).send("404 not found"))
Here's your solution. Remember to place the fallback route at the end of your endpoint list.
router.post('/your-route', function (req, res) {
...
});
router.post('/another-route', function (req, res) {
...
});
router.get('*', function(req, res) {
// This is a fallback, in case of no matching
res.status(404);
res.send('Not found.');
});
I have an Expressjs route which does a db INSERT (using Sequelize) based on some JSON Body params in the request. The bodyParser middleware does a JSON-schema validation on the body and returns an error if it doesn't validate.
The issue here is that something in bodyparser is executing asynchronously, and I'm getting errors such as null values being inserted into the DB (even after a failed validation), and Headers already returned to client errors.
How to best fix this?
The route:
var bodyParser = json_validator.with_schema('searchterm');
router.post('/', bodyParser, function (req, res, next) {
Searchterm.findOrCreate({
where: {searchstring: req.body.searchstring},
defaults: {funnystory: req.body.funnystory},
attributes: ['id', 'searchstring', 'funnystory']
}).spread((searchterm, created) => {
if (created) {
res.json(searchterm);
} else {
res.sendStatus(409);
}
}).catch(next);
});
The middleware:
var ajv = new Ajv({allErrors: true});
var jsonParser = bodyParser.json({type: '*/json'});
module.exports.with_schema = function(model_name) {
let schemafile = path.join(__dirname, '..', 'models', 'schemas', model_name + '.schema.yaml');
let rawdata = fs.readFileSync(schemafile);
let schema = yaml.safeLoad(rawdata);
var validate = ajv.compile(schema);
return function(req, res, next) {
jsonParser(req, res, next);
if (!validate(req.body)) {
res.status(400).send(JSON.stringify({"errors": validate.errors}));
}
}
};
Your middleware calls next too early; change:
return function(req, res, next) {
jsonParser(req, res, next);
if (!validate(req.body)) {
res.status(400).send(JSON.stringify({"errors": validate.errors}));
}
}
to:
return function(req, res, next) {
if (!validate(req.body)) {
res.status(400).send(JSON.stringify({"errors": validate.errors}));
}
}
and your route definition to:
router.post('/', jsonParser, bodyParser, function (req, res, next) { ... });
I am trying to pass some predefined functions in the callback of app.post() method. I am getting next is not defined error. Below is my code. Please suggest where I am doing wrong or am I missing any concept here?
var express = require('express');
var app = express()
app.post('/api/signup', function(req, res) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
where I have each function defined and imported and returning next() after my process.
my validateParams function is below :
validateParams = function(req, res, next) {
console.log("at validator ", req);
next();
}
module.exports = validateParams;
my dbCall function is below :
dbCall = function(req, res, next) {
console.log("at dbCall ", req);
next();
}
module.exports = dbCall;
my sendResponse function is below :
sendResponse = function(req, res) {
console.log("at dbCall ", res);
res.send("Response sent successfully");
}
module.exports = sendResponse;
You probably forgot to add the next argument in your callback.
app.post('/api/signup', function(req, res, next) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
I think you are trying to use validateParams(req, res, next) and dbCall(req, res, next) as middleware functions. In this case, you need something like this:
const validateParams = (req, res, next) => {
// do stuff here
next();
}
const dbCall = (req, res, next) => {
// do stuff here
next();
}
app.post('/api/signup', validateParams, dbCall, function(req, res) {
sendResponse(req, res)
})
You can read more here
Server side code:
var User = require("./models/user");
var express = require('express'),
app = express(),
Account = require("./models/account"),
mongoose = require('mongoose'),
passport = require("passport"),
basicAuth = require('basic-auth'),
bodyParser = require("body-parser"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"); //libraries
mongoose.connect("mongodb://localhost/test");
app.set('view engine', 'ejs'); //using engine of ejs file
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "kiss my ass",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// AUTH Routes
//create account success
app.get('/success', function (req, res) {
res.render('success');
});
// deleteUser form
app.get("/delete", function(req, res, next) {
res.render("deleteuser");
});
app.get("/viewall", function(req, res, next) {
res.render("viewall");
});
//view all User form
app.get('/view', function (req, res) {
console.log('getting all user');
Account.find({})
.exec(function(err, results) {
if(err) {
res.send('error has occured');
}else{
console.log(results);
res.json(results);
}
});
});
app.get('/viewall/:id', function (req, res) {
console.log('getting one user');
Account.findOne({
_id:req.params.id
})
.exec(function(err, account) {
if(err) {
res.send('error occured');
}else{
console.log(account);
res.json(account);
}
})
})
// LOGIN for user
// render login form
app.get("/", function(req, res) {
res.render("login");
});
//login for user
//middleware
app.post("/login", passport.authenticate("local", {
successRedirect: "http://localhost:8082/viewImage.html",
failureRedirect: "http://localhost:8081/error"
}), function(req, res) {
});
//logout from basicauth
app.get('/logout', function (req, res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.sendStatus(401);
// res.send("<a href='/login'>Show Users</a>");
});
//basicauth for admin login
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'admin' && user.pass === 'admin123') {
return next();
} else {
return unauthorized(res);
};
};
//LOGIN for admin
//render login form
app.get("/register", auth, function(req, res) {
res.render("register");
});
// register post
app.post("/register", function(req,res){
Account.register(new Account({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render('/register');
}
passport.authenticate("local")(req, res, function(){
res.redirect("/success");
});
});
});
app.listen(8081, function () {
console.log('ImageViewer listening on port 8081!');
});
JS code:
$scope.delete = function (data) {
if (confirm('Do you really want to delete?')){
$window.location.reload();
$http['delete']('/viewall/' + data._id).success(function() {
$scope.users.splice($scope.users.indexOf(data), 1);
});
}
};
html code:
<tr ng-repeat="user in users | filter:searchBox | orderBy:'+username'">
<td>{{user._id}}</td>
<td>{{user.username}}</td>
<td><button class="btn btn-primary" ng-click="delete(user)">Delete</button></td>
This is the error i got:
DELETE
XHR
http://localhost:8081/viewall/5784919136ccb93d0ba78d4b [HTTP/1.1 404 Not Found 8ms]
But when i run the url of http://localhost:8081/viewall/5784919136ccb93d0ba78d4b and it does give me the data:
{"_id":"5784919136ccb93d0ba78d4b","username":"qs","__v":0}
Anybody can help me? don't know what's with the error404 when i'm able to get the data.
You have no route for '/viewall/:id' with DELETE verb. So you should add route with DELETE verb. like
app.delete('/viewall/:id',function(req,res){
// rest of code here
// assume your model name Account
Account.remove({ _id: req.params.id },function(err,doc) {
if(err) {
return res.status(400).send({msg: 'Error occurred during delete account'});
}
return res.status(200).send({msg: 'Successfully deleted'});
});
}
and you should reload after success in your angular controller. like
$http['delete']('/viewall/' + data._id).then(function(response) {
$scope.users.splice($scope.users.indexOf(data), 1);
$window.location.reload();
});
Things are sort of working but, for some reason, I can't get the user_id into the URL, all I get is a literal ":user_id" like so:
here is the code in the my users.js route file
var main = require('../main');
exports.getAllUsers = function(req, res) {
var db = main.db();
db.collection('users').find().toArray(function(err, items) {
res.json(items);
});
};
exports.routeUserToTheirHome = function(req, res, next) {
res.json(req.user);
};
and here is the code in my main.js file:
app.param('user_id', function(req, res, next, user_id) {
// typically we might sanity check that user_id is of the right format
User.find(user_id, function(err, user) {
if (err) {
return next(err);
}
if (!user) {
return new Error("no user matched");
}
req.user = user;
next();
});
});
app.use('/users/:user_id/home', users.routeUserToTheirHome);
exports.routeUserToTheirHome = function(req, res, next) {
req.user.user_id = req.params.user_id;
res.json(req.user);
};
I figured out what the problem was, it was that I had this:
app.post('/login', passport.authenticate('local', {
successRedirect : 'users/:user_id/home',
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
next();
});
when in fact, I needed this:
app.post('/login', passport.authenticate('local', {
successRedirect : 'users/' + '5464370621a2569c18880876' +'/home',
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
next();
});
clearly I don't know what I am doing. The question now is, where do I get the user_id from, instead of hardcoding it?
here is the solution:
app.post('/login', passport.authenticate('local', {
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
res.redirect('users/' + req.user._id +'/home');
next();
});