ı have tis error
:can't send headers after they send.ı get from url and browser redireck url but ı dont get content from home.html
ı have tis error
:can't send headers after they send.ı get from url and browser redireck url but ı dont get content from home.html
var path = require('path');
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io').listen(server);
var session = require('express-session'); //session işlemleri
mongodb = require('mongodb'); //veritabanı işlemleri
var mongoclient = mongodb.MongoClient;
var bodyparser = require('body-parser'); //form submit için
var multer = require('multer'); //dosya yükleme
app.use("/style", express.static(__dirname + "/style"));
app.use("/images", express.static(__dirname + "/images"));
app.use("/scripts", express.static(__dirname + "/scripts"));
app.use(bodyparser.urlencoded({
'extended': 'true'
}));
app.use(bodyparser.json());
app.use(session({
'secret': 'hhhhh',
resave: true,
saveUninitialized: true
}));
//register
app.get("/register", function(req, res) {
if (req.session.userid) {
res.redirect("/home")
};
res.sendFile(__dirname + "/register.html");
});
//register
//register post
app.post("/register", function(req, res) {
var reguserame = req.body['username'].trim();
var regpassword = req.body['password'].trim();
mongoclient.connect("mongodb://127.0.0.1/deneme", function(err, db) {
if (err) {
res.sendStatus("veritabanı ile ilgili bir hatta algılandı");
} else {
var users = db.collection("users");
users.count({
"name": reguserame
}, function(err, count) {
if (count == 1) {
res.send("bu kullanıcı adı daha önce alınmış");
res.end();
} else {
var kayit = db.collection("users").insert({
"name": reguserame,
"pass": regpassword
});
if (kayit) {
res.send('kayıt basarılı giriş yap');
} else {
res.send("kayit basarısız");
}
res.end();
}
});
}
});
});
//register post
//logout
app.get("/logout", function(req, res) {
req.session.destroy();
res.redirect("/login");
});
//logout
app.get("/login", function(req, res) {
if (req.session.userid) {
res.redirect("/home");
}
res.sendFile(__dirname + "/login.html");
});
//login kontrol
app.post("/login", function(req, res) {
var username = req.body['username'].trim();
var password = req.body['password'].trim();
mongoclient.connect("mongodb://127.0.0.1:27017/deneme", function(err, db) {
db.collection("users").find({
"name": username,
"pass": password
}).toArray(function(err, result) {
var sayisi = result.length;
///uye kontrol
if (sayisi == 1) {
res.status(200);
req.session.userid = result[0]._id;
res.redirect("/home");
} else {
res.sendStatus("hatalı parola");
res.end();
}
db.close();
//uye kontrol
});
});
});
//home sayfası
app.get("/home", function(req, res) {
if (req.session.userid) {
res.sendFile(path.join(__dirname + "/home.html"));
res.end();
} else {
res.send("henüz giriş yapılmamış");
res.end();
}
});
//login kontrol
app.use(function(req, res) {
res.status("404");
res.write("<div style='height:100%; top:0px; left:0px; position:absolute; text-align: center; vertical-align: center; width:100%; background: #eee;'><h1 style='border:1px solid #999; color:#f63; margin-top:20%;'>sayfa yok</h1></div>");
res.end();
});
res.redicert("/home") this row by ı get error
> Blockquote
///please
In this part of the code, it is sending the status 200 and the redirect wants to send status 302:
res.status(200);
req.session.userid=result[0]._id;
res.redirect("/home");
It can't send the status 302 because it already sent the status 200. Try removing the res.status(200).
There are other trouble spots like this:
if(req.session.userid){ res.redirect("/home");}
res.sendFile(__dirname+"/login.html");
It either needs a return after the redirect() or the sendFile() part needs to go in an else block. The redirect() is sending 302 and then the sendFile() executes and wants to send a 200.
Not sure if this is all of your problemms, but you have a spelling mistake
// res.redicert("/home") -->
res.redirect("/home")
Related
I am learning nodejs and I want to check if user is logged in by checking session.login value but when session.login is created and then user is redirected to main page, session.login is again undefined.
emit 'logged' is just redirecting user to the dashboard but dashboard checks if session.login exists, it shows undefined and user is redirected again to the login page.
var app = require('express')(); //load and initialize express
var http = require('http').Server(app); //create http server
var io = require('socket.io')(http); //add socket to http server
var path = require('path') //initialize path module
var port = 3000; //define port
var mysql = require('mysql'); //load mysql module
var session = require('express-session'); //sessions module
var login; //login
var md5 = require('md5');
//connecting to the database
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
con.connect((error) => {
if(error) console.log('Error with database connection.');
else console.log("Connected to the database!");
});
//define default path
app.use(require('express').static(path.join(__dirname, 'public')));
//session
app.use(session({
secret: 'randomstringhere',
resave: false,
saveUninitialized: false,
cookie: {
}
}));
app.get('/', (req, res) => {
if (req.session.login) {
res.redirect('/dashboard');
}
else {
res.sendFile(__dirname + '/views/login.html');
console.log("Someone has joined to the server.");
io.on('connection', (socket) => {
//login
socket.on('login', (login, password) => {
con.query('SELECT * FROM users WHERE login="'+login+'" AND password="'+md5(password)+'"', (error, results, fields) => {
if (error) console.log('Error');
if (results[0]) {
req.session.login = results[0].login;
console.log(req.session.login+": Succesfully logged.");
req.session.save();
socket.emit('logged', 'You will be logged, please wait!');//redirects to /dashboard
}
else {
socket.emit('cant login', 'Login or password incorrect!');
console.log("Incorrect login or password.");
}
});
});
});
}
});
app.get('/dashboard', (req, res) => {
if (req.session.login) {
res.sendFile(__dirname + '/views/index.html');
console.log(req.session.login + " has joined to the server.");
io.on('connection', (socket) => {
socket.on('message', (msg) => {
io.emit('message', req.session.login + ": " + msg);
console.log(req.session.login + ": " + msg);
});
//logout
socket.on('logout', () => {
socket.emit('logging out');
req.session.destroy();
});
});
}
else {
res.redirect('/');
}
});
well a want to make a simple chat system, and for that i have to show
all clients witch are connected.i try sivrel techniques and it dons't work.
i tried to emit a socket when a client connect and it dons't work.
that's what i tried:
app.post('/login', (req, res)=>{
let user = req.body.username
let pass = req.body.password
console.log("le user est = " + user + " \nle password est = " + pass);
connection.query('SELECT * FROM user WHERE username = ? AND password = ?', [user,pass], function (error, results, fields) {
if (error) throw error;
console.log(results.length);
console.log(results[0]);
if (results.length==1){
const user_id = results[0]
io.sockets.emit('new_user',{user:results[1]})
req.login(user_id,(err)=>{
res.redirect('/home');
})
}else {
res.redirect('/');
}
});
});
and that the full code :
server.js:
let express = require('express');
let app = express();
let bodyParser = require('body-parser')
let server = require('http').createServer(app);
var io = require('socket.io')(server);
let session = require('express-session')
let MySQLStore = require('express-mysql-session')(session);
let passport = require('passport');
let mysql = require('mysql');
let hbs = require('hbs')
var options = {
host: 'localhost',
user: 'root',
password: '',
database: 'robot'
};
var sessionStore = new MySQLStore(options);
let connection = mysql.createConnection(options);
connection.connect(function(err) {
if (err) {
console.error('MYSQL error connecting : ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
app.use(session({
secret: 'ldifgquoqjfejg',
store: sessionStore,
//comme elle change que lorsque on modéfie la session
resave: false,
saveUninitialized: false,
//cookie: { secure: true }
}))
app.use(passport.initialize());
app.use(passport.session());
//hbs configure
app.set('view engine', 'html');
app.engine('html', hbs.__express);
hbs.registerPartials(__dirname + '/views/partials');
hbs.localsAsTemplateData(app);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res)=>{
res.render('login');
});
app.get('/home', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('index');
});
app.get('/robot', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('robot');
});
app.get('/userlist', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('listeuser');
});
app.get('/history', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('history');
});
app.get('/chat', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('chat');
});
app.get('/cam', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('cam');
});
app.get('/bras', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('bras');
});
app.get('/base', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('base');
});
app.get('/ajout', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('ajout');
});
app.get('/Logout', (req, res)=>{
req.logout();
req.session.destroy();
res.redirect('/');
});
app.post('/login', (req, res)=>{
let user = req.body.username
let pass = req.body.password
console.log("le user est = " + user + " \nle password est = " + pass);
connection.query('SELECT * FROM user WHERE username = ? AND password = ?', [user,pass], function (error, results, fields) {
if (error) throw error;
console.log(results.length);
console.log(results[0]);
if (results.length==1){
const user_id = results[0]
io.sockets.emit('new_user',{user:results[1]})
req.login(user_id,(err)=>{
res.redirect('/home');
})
}else {
res.redirect('/');
}
});
});
passport.serializeUser(function(user_id, done) {
done(null, user_id);
});
passport.deserializeUser(function(user_id, done) {
done(null, user_id);
});
//socket
io.on('connection', (socket)=>{
socket.emit('user','data')
});
//socket
server.listen(8000);
app.use(express.static('./views'));
function authenticationMiddleware(){
return(req, res, next)=>{
//console.log('req.session.passport.user: ${JSON.stringify(req.session.passport)}')
if (req.isAuthenticated()) return next();
res.redirect('/')
}
}
and the chat.html
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
socket = io.connect('http://localhost:8000')
socket.on('new_user',(data)=>{
document.getElementById('ilyes').innerHTML=data.user
})
</script>
When I try to run my code it gives me Reference Error: LocalStrategy is not defined.
This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.
I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.
/***********
Modules
***********/
//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;
/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/js', express.static(__dirname + '/js'));
/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());
/***********
Database
***********/
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + usr + ':' + pwd + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Models
***********/
//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
user_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
//Create model object
var User = mongoose.model('user', UserSchema);
/***********
Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.get('/home', function (req, res, next) {
res.sendFile(__dirname + '/home.html');
});
app.post('/login', passport.authenticate('local'),
function(req, res) {
res.redirect('/home');
});
/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if(user !== null) {
var isPasswordCorrect = bcrypt.compareSync(password, user.password);
if(isPasswordCorrect) {
console.log("Username and password correct!");
return done(null, user);
} else {
console.log("Password incorrect!");
return done(null, false);
}
} else {
console.log("Username does not exist!");
return done(null, false);
}
});
}
));
/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(err, user);
});
app.post('/register', function (req, res, next) {
var password = bcrypt.hashSync(req.body.password);
req.body.password = password;
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function() {
console.log('Server running at port ' + port);
});
The reason is you have defined var LocalStratgy, not LocalStrategy.
You're using it like this-
https://www.npmjs.com/package/passport-local-mongoose#configure-passportpassport-local
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
But I suggest you to use it like this -
https://www.npmjs.com/package/passport-local-mongoose#simplified-passportpassport-local-configuration
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
how can pass a global variable in node from a file to a module ?
I'm trying with a db variable that is a database mongo connection.I copy the contents of file for the connections that i was trying to do, but did not work, have no errors in console; just in my browser got error 500.
app.js
var express = require('express');
var accounts = require('./routes/accounts');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use('/accounts', accounts);
app.use(function(req, res) {
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// custom 500 page
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
var mongoUtil = require( './mongoUtil');
mongoUtil.connectToServer( function( err ) {
app.listen(app.get('port') , function() {
console.log('Express started in ' + app.get('env') +
' mode on http://localhost:' + app.get('port') +
'; press Ctrl-C to terminate.');
});
} );
mongoUtils.js
var MongoClient = require( 'mongodb' ).MongoClient;
const assert = require('assert');
var dbclass = module.exports = {
db : null,
connectToServer: function( callback ) {
var url = 'mongodb://localhost:27017/crm1';
MongoClient.connect(url, function(err, db) {
if(err) throw err;
console.log("Connected successfully to server");
dbclass.db = db;
});
},
getDb: function() {
return dbclass.db;
}
};
/router/accounts.js
var express = require('express');
var router = express.Router();
var db = .... ??? ;
router.get('/', function(req, res) {
findDocuments(db, function() {
db.close();
});
});
router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('accounts');
// Find some documents
collection.find().toArray(function(err, docs) {
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
module.exports = router;
A working and not awful way to do this is to not export the router directly, but a generator for it. Multiples syntax are possibles for the generator, I ve chosen to show you a example using a similar pattern than the one you used for your MongoUtils:
app.js:
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
var mongoUtil = require( './mongoUtil');
mongoUtil.connectToServer( function( err ) {
var accounts = require('./routes/accounts');
accounts.init(mongoUtils.getDb());
app.use('/accounts', accounts.getRouter());
app.use(function(req, res) {
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// custom 500 page
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port') , function() {
console.log('Express started in ' + app.get('env') +
' mode on http://localhost:' + app.get('port') +
'; press Ctrl-C to terminate.');
});
} );
/router/accouts.js:
var express = require('express');
var router = express.Router();
function init(db) {
router.get('/', function(req, res) {
findDocuments(db, function() {
db.close();
});
});
router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('accounts');
// Find some documents
collection.find().toArray(function(err, docs) {
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
}
function getRouter() {
return router;
}
module.exports = {
init: init,
getRouter: getRouter
};
I've rewrittenthe code following #DrakaSAN ideas; my code had errors, i've changed in a betther way:
app.js
let express = require('express');
let app = express();
app.set('port', process.env.PORT || 3000);
let dbMongo = require( './db/dbMongoNative');
dbMongo.init ( function( error ) {
if (error)
console.error(error);
let accounts = require('./routesMongoNative/accounts');
accounts.init();
app.use('/accounts', accounts.getRouter());
app.get('/',function(req, res) {
res.send('hello');
});
app.use(function(req, res) {
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// custom 500 page
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port') , function() {
console.log('Express started in ' + app.get('env') +
' mode on http://localhost:' + app.get('port') +
'; press Ctrl-C to terminate.');
});
} );
/db/dbMongoNative.js
var MongoClient = require( 'mongodb' ).MongoClient;
module.exports.init = function (callback) {
var url = 'mongodb://localhost:27017/crm1';
MongoClient.connect(url, function (error, db) {
if (error) {
console.error(error);
}
console.log("Connected successfully to server");
module.exports.db = db;
console.log('end connect');
callback (error);
});
};
/routesMongoNative/accounts.js
var express = require('express');
var router = express.Router();
var dbMongo = require( '../db/dbMongoNative' );
let db = dbMongo.db; // connection was done before in app
let findAll = function(res, db ) {
db.collection('accounts').find( {}).toArray( function( error, result ) {
if (error) throw error;
res.json(result);
});
};
function init() {
router.get('/', function(req, res) {
findAll(res, db );
});
}
function getRouter() {
return router;
}
module.exports = {
init: init,
getRouter: getRouter
};
I am trying to remove the # sign on the URL using html5mode by stating the location provider html5mode to true
$locationProvider.html5Mode(true);
I also did configured my server.js file to serve my static files and my index.html as below
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
port = process.env.PORT || 8080;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen('8080');
console.log('The magic happens on port 8080');
At this point, everything works fine from localhost:8080 to other navigation such as localhost:8080/login even when I refreshed the page, it is still working fine.
It it not working during any API fetch statement is being called. Below is my routes.js
route.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db);
User = require('./models/user.js')(db);
module.exports = function(app) {
app.route('/api/user')
.get(function(req, res, next) {
User.find(function(err, user){
if(err)
res.json(err);
res.json(user);
});
})
.post(function(req, res, next) {
var error_return = [{response:'User Existed'},{response:'Invalid Username or Password'},{response:'Server Error'}];
if(req.body.type === "local"){
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
newUser.save(function(error, result){
if(error)
res.json(error_return[2]);
res.json({response:result});
});
return;
}
res.json(error_return[0]);
});
}else if(req.body.type === "login"){
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)){
res.json(error_return[1]);
return;
}
res.json({response:user});
});
}
});
};
Previously before enabling html5mode, my files in require('./app/routes.js')(app); is running smoothly, after enabling, it is not even being called. Have I missing something in my code?
All your requests are going to public/index.html right now.
Modify your code to allow /api/ requests to go to the routes
app.use('/api', bodyParser.json(), require('./app/routes.js'));
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.listen('8080');
console.log('The magic happens on port 8080');
routes.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db),
User = require('./models/user.js')(db),
router = require('express').Router();
module.exports = router;
router.route('/user')
.get(function (req, res, next) {
User.find(function (err, user) {
if (err) res.json(err);
res.json(user);
});
})
.post(function (req, res, next) {
var error_return = [{
response: 'User Existed'
}, {
response: 'Invalid Username or Password'
}, {
response: 'Server Error'
}];
if (req.body.type === "local") {
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
newUser.save(function (error, result) {
if (error) res.json(error_return[2]);
res.json({
response: result
});
});
return;
}
res.json(error_return[0]);
});
} else if (req.body.type === "login") {
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)) {
res.json(error_return[1]);
return;
}
res.json({
response: user
});
});
}
});