I am trying to move my angular controller code into a separate file and the JS file is throwing errors like angular not recognised. It was working when the controller was in the same file
html file
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>title </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js'>
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular-resource.min.js'>
<script src="public/js/ang.js"></script>
</head>
<body ng-controller="democontroller">
<h1>title </h1>
<p>Welcome to title </p>
</body>
</html>
ang.js file
var app = angular.module('demo', []);
app.controller("democontroller", function($scope,$http,$window) {
alert("hi");
});
node's app.js file
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(8000, function(){
console.log("ready on port 8000");
});
module.exports = app;
We figured it out in the chat I believe the code was missing closing </script> tags.
Related
this is my code I am running the server but I can't get the page index.html
the error is
app.get('/',function(request,response){
console.log("/");
response.sendFile(__dirname+"/views/index.html");
})
The error is
This 127.0.0.1 page can’t be found
No webpage was found for the web address: http://127.0.0.1:5000/home
HTTP ERROR 404
I dont think the server is getting the get request. I don't see the console.log() getting called.
The entire code:
var http = require("http");
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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(express.static(__dirname+"/"));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.get('/',function(request,response){
console.log("/");
res.sendfile('views/index.html', {root: __dirname });
});
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// http.createServer(function (request, response) {
// // Send the HTTP header
// // HTTP Status: 200 : OK
// // Content Type: text/plain
// response.end('Hello World\n');
// response.writeHead(200, {'Content-Type': 'text/plain'});
// // Send the response body as "Hello World"
// }).listen(8081);
app.listen(5000);
// Console will print the message
console.log('Server running at http://127.0.0.1:5000/');
module.exports =app;
In your error, http://127.0.0.1:5000/home is not found that mean you did not define /home route. So you need to update app.get('/') route as following
app.get('/home?',function(request,response){
console.log("Url: " + request.url);
response.sendfile('views/index.html', {root: __dirname });
});
Try this
app.use('/', routes);
app.use('/users', users);
//add your route to get file
app.get('/',function(request,response){
console.log("/");
response.sendfile('views/index.html', {root: __dirname });
});
See the doc understand it correctly res.sendFile
Hit this URL http://127.0.0.1:5000/ to get your file in browser
I am new in MEAN technology and Developing Web APP. I established the
Connection and login successfully. I want to establish the session after login
But I don't know how to established the session in MEAN app.
Connection established using app.js
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 routes = require('./routes/index');
var api = require('./routes/api');
var users = require('./routes/users');
// database connectivity
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ditroapp');
var db = mongoose.connection;
db.on('error', function (err) {
console.log('mongo connection error', err);
});
db.once('open', function () {
console.log('mongo connected.');
});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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('/', routes);
app.use('/api', api);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
and here is code in controller.js using this I login successful.
$scope.loginpage = function(){
$http({
method: 'POST',
url: '/api/login',
data: {email:$scope.email, password:$scope.password}
}).then(function successCallback(response) {
if(response.data.error)
{
alert("Invalid email pasword");
}
else
{
$scope.dp = response.data;
$localStorage.pp = $scope.dp;
//console.log($localStorage.pp)
$location.path('/addseat');
}
}, function errorCallback(response) {
alert("Invalid email pasword");
});
}
I'm starting learning Express and Angularjs. In the project, I want to render HTML at the server side and bind data via Angularjs but it didnt work. I saw that ng-repeat is disable in browser
<body ng-app="photoApp" class="ng-scope">
<h1>Express</h1>
<p>Welcome to Express</p>
<!-- ngView: -->
<div ng-view="" class="ng-scope">
<div id="photos" class="ng-scope">
<!-- ngRepeat: photo in vm.photos -->
</div>
</div>
</body>
, therefore no data is showed. Please help me to fix that, thanks in advanced!
Project Structure
photo
--public
----javascript
------lib
------photoApp.js
--routes
----index.js
----photo.js
--views
----partials
------photo-list.pug
----error.pug
----index.pug
----layout.pug
--app.js
Server-side code:
app.js
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 routes = require('./routes/index');
var users = require('./routes/users');
var photos = require('./routes/photos');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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('/', routes);
app.use('/users', users);
app.use('/photos', photos);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/partials/:name', function(req, res, next){
var name = req.params.name;
res.render('partials/' + name);
});
module.exports = router;
photos.js
var express = require('express');
var router = express.Router();
var photos = [];
photos.push({
name: 'Node.js Logo',
path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
name: 'Ryan Speaking',
path: 'http://nodejs.org/images/ryan-speaker.jpg'
});
router.get('/api/get-all', function(req, res) {
res.json(photos);
});
router.get('/', function(req, res) {
res.render('photos');
});
module.exports = router;
layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='javascripts/lib/angular.js')
script(src='javascripts/lib/angular-route.js')
script(src='javascripts/photoApp.js')
body(ng-app="photoApp")
block content
index.pug
extends layout
block content
h1= title
p Welcome to #{title}
div(ng-view)
photo-list.pug
#photos
.photos(ng-repeat="photo in vm.photos")
h2 {{photo.name}}
img(src="{{photo.path}}")
Client-side code:
photoApp.js
var photoApp = angular.module('photoApp', ['ngRoute']);
photoApp.controller('PhotoListController', PhotoListController);
photoApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'partials/photo-list',
controller: 'PhotoListController',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
}]);
function PhotoListController($scope, $http) {
var vm = this;
vm.getAllPhotos = getAllPhotos;
function getAllPhotos(){
$http.get('/photos/api/get-all')
.success(function(response) { vm.photos = response.photos; })
.error(function() { console.log('Error when getting all photos'); });
}
}
I try to create a SPA with angular on a node/express server. Please bear with me, I am confused. View engine is ejs. On my app.js I have
var routes = require('./routes/index');
app.use('/', routes.list);
index.js contains
exports.list = function(req, res){
res.render('index', {
title: 'Home'
});
};
so it can render index.ejs that contains
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="./public/javascripts/angular.min.js"></script>
<script src="./public/javascripts/angular-route.min.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
templateUrl: './views/home.ejs',
controller: 'homeController'
})
.when(' /about', {
// route for the about page
templateUrl: './views/about.ejs',
controller: 'aboutController'
})
)}
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
</script>
<title><%= title %></title>
<div ng-view></div>
<li>Home</li>
<li>About</li>
home.ejs and about.ejs are like
<h1>About Page</h1>
<p>{{ message }}</p>
1- I cannot load the angular.min.js and angular-route.min.js. I get angular is not defined for the var app = angular.module('app', ['ngRoute']); line in index.ejs file and Unexpected token < for <!DOCTYPE html> on the same file.
2- home.ejs and about.ejs dont load
3- I replace with app.use('/#', routes.list); on app.js and <a href="#"> <a href="#about"> on the index.ejs and I get error 404. Why the # character on the URL causes problems?
4- Should I also create routes for about like var about = require('./routes/about'); and app.use('/about', about.list);? Or is an SPA, so routes are not necessary because they will cause page loads?
Sorry for the big question.
Thanks in advance
UPDATE
on the index.ejs file I changed the app to sp , so no conflicts occur, but the same problems remain.
UPDATE 2
the whole app.js is
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes.list);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(4800);
module.exports = app;
am using passport to handle the log in process in my app but, am not using a server side route which is a submitted from instead, am using an xhr post, but because of that i got an issue that i couldn't determine.
here is the code of my app.js:
module.exports = function(db){
var express = require('express');
var mongoose = require('mongoose'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
var config = require('./config/config')[env];
require('./config/express')(app);
require('./config/db');
var User = mongoose.model('User');
passport.use(new LocalStrategy(
function(username, password, done){
User.findOne({userName:userName}).exec(function(err, user){
if(user){
return done(null, user);
console.log('found the user');
}else{
return done(null, false);
console.log('user not found');
}
})// query of findOne
}
));
passport.serializeUser(function(user, done){
if(user){
done(null, user._id);
}
});
passport.deserializeUser(function(id, done){
User.findOne({_id:id}).exec(function(err, user){
if(user){
return done(null, user);
}else
return done (null, false);
})
})
require('./config/routes')(app);
return app;
}
which is i don't get any of the log messages in my console, made me think i never query the database.
and here is the code of my route that i require at the end of the app.js
app.post('/login', function(req, res, next){
var auth=passport.authenticate('local', function(err, user){
if(err){return next(err);}
if(!user){res.send({success: false})}
req.logIn(user, function(err){
if(err){return next(err); }
res.send({success: true, user:user});
})
})
auth(req, res, next);
})
i handle the client side log in using angular.js so here is the controller code :
angular.module('app').controller('mvLoginCtrl', function($scope, $http){
$scope.signin = function(username, password){
$http.post('/login', {username:username, password:password}).then(function(response){
if(response.data.success){
console.log('logged in');
}else{
console.log('failed to log in');
}
})
}
})
the only message i got in my browser console is the one i logged in my mvLoginCtrl controller "failed to log in" and i can't tell where my code fail and if it query the data base or not .but each attempted to log in with exist username i get the fail message any help or explanation is appreciated.
express.js located ./config/express.js
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
module.exports = function(app){
// view engine setup
app.set('views', path.join(__dirname, '../views'));
//app.set('views', config.rootPath + 'views');
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.session({secret: 'myapp mobile unicorns'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, '../public')));
//app.use(express.static(config.rootPath + 'public'));
/*
*Middleware to modifiy the header.
*/
app.use(function(req,res,next){
res.set ('myapp-Powered-By' , 'mycompany');
next();
});
}
the log of the response object returned from the post request in the mvLoginCtrl controller
Object {data: "<!DOCTYPE html><html><head><title></title>
<link re…/app/admin/mvPushCtrl.js"></script></body></html>",
status: 200, headers: function, config: Object, statusText: "OK"}config:
Objectdata: "<!DOCTYPE html><html><head><title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
<link rel="stylesheet" href="/vendor/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/vendor/toastr/toastr.min.css">
</head><body ng-app="app"><h1>userName is not defined</h1><h2></h2><pre>ReferenceError: userName is not defined?
at Strategy._verify (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\app.js:21:36)?
at Strategy.authenticate (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport-local\lib\strategy.js:90:12)?
at attempt (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport\lib\middleware\authenticate.js:337:16)?
at authenticate (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport\lib\middleware\authenticate.js:338:7)?
at C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\config\routes.js:24:6?
at callbacks (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:164:37)?
at param (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:138:11)?
at pass (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:145:5)?
at Router._dispatch (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:173:5)?
at Object.router (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:33:10)</pre><script type="text/javascript" src="/vendor/jquery/dist/jquery.min.js"></script><script type="text/javascript" src="/vendor/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/vendor/toastr/toastr.js"></script><script type="text/javascript" src="/vendor/angular/angular.min.js"></script>
<script type="text/javascript" src="/vendor/angular-resource/angular-resource.min.js"></script><script type="text/javascript" src="/vendor/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/app/app.js"></script><script type="text/javascript" src="/app/main/mvMainCtrl.js"></script>
<script type="text/javascript" src="/app/account/mvLoginCtrl.js"></script><script type="text/javascript" src="/app/account/mvIdentity.js"></script>
<script type="text/javascript" src="/app/common/mvNotifier.js"></script><script type="text/javascript" src="/app/account/mvAuth.js"></script>
<script type="text/javascript" src="/app/admin/mvPushCtrl.js"></script></body></html>
"headers: function (c){a||(a=vc(b));return c?a[I(c)]||null:a}status: 200statusText: "OK"__proto__: Object mvLoginCtrl.js:22
failed to log in