Why won't my express.js run? - javascript

I have an express.js app that get to this:
node app.js
info - socket.io started
And it won't get any further, if anyone can explain why this happens and how to fix it, it would be greatly appreciated. I believe the error is in my app.js which is posted here:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var http = require('http');
var db = mongojs('127.0.0.1:27017/mySpendingDB', ['users']);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var path = require('path');
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function (req, res) {
res.render('login.html', {
title: 'Login'
});
});
app.get('/index', function (req, res) {
res.render('index.html', {
title: 'Daily'
});
});
app.get('/monthly', function (req, res) {
res.render('monthly.html', {
title: 'Monthly'
});
});
app.get('/yearly', function (req, res) {
res.render('yearly.html', {
title: 'Login'
});
});
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
var user = "";
io.sockets.on('connection', function (socket) {
console.log('socket.io started');
socket.on('login', function (data) {
var checkUser = db.users.find(data);
if (checkUser !== null) {
user = checkUser.username;
app.get('/index', function (req, res) {
res.direct('/index');
});
socket.emit('uploadList', checkUser.total);
}
});
socket.on('purchaseLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.purchase.save(data);
});
socket.on('depositLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.deposit.save(data);
});
socket.on('goLogout', function (data) {
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
});
socket.on('goIndex', function (data) {
app.get('/index', function (req, res) {
res.redirect('/index');
});
});
socket.on('goMonthly', function (data) {
app.get('/monthly', function (req, res) {
res.redirect('/monthly');
});
var monTot = db.users.find({
username: user
}).monthlyTotal;
socket.emit('wentMonthly', monTot);
});
socket.on('goYearly', function (data) {
app.get('/index', function (req, res) {
res.redirect('/index');
});
var yearTot = db.users.find({
username: user
}).yearlyTotal;
socket.emit('wentYearly', yearTot);
});
socket.on('registered', function (data) {
db.users.save(data);
app.get('/index', function (req, res) {
res.redirect('/index');
});
});
});
app.listen(3000);

You should be using server.listen(port) instead of app.listen(port). Using app.listen() will only start your Express application, while you also want the HTTP server that socket.io is piggybacking on to start.

Related

Additional Route

I want to add a second route to a /privacy page, but it is not working. I get "Cannot GET /privacy.html" error. Any suggestions??
This code does not respond with the privacy.html content
app.get('/privacy', function(req, res) {
res.sendFile(__dirname + "/privacy.html");
});
Here is my app.js code
//jshuint esversion: 6
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.get('/privacy', function(req, res) {
res.sendFile(__dirname + "/privacy.html");
});
app.post("/", function(req, res) {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const emailAddress = req.body.emailAddress;
const data = {
members: [
{
email_address: emailAddress,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
};
const jsonData = JSON.stringify(data);
const url = "https://us.api.mailchimp.com/3.0/lists/bb80b745a8"
const options = {
method: "POST",
auth: "meshiaR:93d648-u"
};
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
res.sendFile(__dirname + "/success.html");
} else {
res.sendFile(__dirname + "/failure.html");
}
response.on("data", function(data){
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
});
// app.post("/privacy", function(req, res){
// res.sendFile(__dirname + "/privacy.html");
// });
app.post("/failure", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function(){
console.log("Server is now running on port 3000");
});
This is how I achieve this kind of tasks.
var path = require('path');
app.get('/privacy', function(req, res) {
res.sendFile(path.join(__dirname + '/privacy.html'));
});
BTW, check your privacy.html is available in correct path.

TypeError: Cannot read property 'db' of undefined

My code
I am doing exactly as in the video but each time this issue occurs please help!
here is the link to the video: https://www.youtube.com/watch?v=ipkLgbtS0LU&list=PLsY8aWop1tAH2mtv7jSTt6zr5Sfpu1WrM&index=3
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use('/static', express.static(__dirname + '/static'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
var MongoClient = require("mongodb").MongoClient
MongoClient.connect("mongodb://localhost:27017", {useNewUrlParser: true, useUnifiedTopology: true}, function(error, client){
var blog = client.db("blog");
console.log("DB connected");
app.get('/', function(req, res){
res.send("Hello world")
});
app.get("/admin/dashboard", function(req, res) {
res.render("admin/dashboard");
});
app.get("/admin/posts", function(req, res) {
res.render("admin/posts");
});
app.post("/do-post", function(req, res){
blog.collection("posts").insertOne(req.body, function(error, document){
res.send("Posted Successfully!")
});
});
app.listen(3000, function() {
console.log("Server Connected");
})
}) ```
Try this:
var blog = client.collection("blog");
console.log("DB connected");
client.db does not exist
In fact your 'client' is your database so you should rename it to db like so:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
if (err) {
throw err;
}
db.collection('mammals').find().toArray(function(err, result) {
if (err) {
throw err;
}
console.log(result);
});
});
Source: https://expressjs.com/en/guide/database-integration.html#mongodb

My Node.js gets an Route.post() got a object Undefined error

I did a simple modularization through Node.js.
And I tried to do an api test through Postman, but my nodemon says that the following error occurred.
error
Error: Route.post() requires a callback function but got a [object Undefined]
at Route.
routes/router.js
const express = require('express');
const route = express.Router();
const user = require('../controller/user');
route.route('/user')
.post(user.createUser)
.get(user.readUser)
.put(user.updateUser)
.delete(user.deleteUser)
module.exports = route;
controller/user.js
exports.createUser = function (req, res) {
res.send('user create.')
}
exports.readUser = function (req, res) {
res.send('user read.')
}
exports.updateUser = function (req, res) {
res.send('user update.')
}
exports.deleteUser = function (req, res) {
res.send('user delete.')
}
server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const router = require('./routes/router');
app.use(router);
app.listen(port, err => {
if(err) console.log(err)
else console.log('server on');
});
What's wrong with me?
I would suggest transforming your current code (controller/user.js) to:
module.exports = {
createUser: function(req, res){
res.send('User created')
},
readUser: function (req, res) {
res.send('Viewing user.')
},
updateUser: function (req, res) {
res.send('User updated.')
},
deleteUser: function (req, res) {
res.send('User deleted.')
}}

Can't set headers after they are sent error

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

Data is not delete in mongodb with angularJS

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();
});

Categories

Resources