So I am getting this error: "GET http://localhost:8000/blogs/undefined net::ERR_EMPTY_RESPONSE angular.js:12587".
It happens when I go to my main blog page and when I go to a blog category page. Looking at the network tab I get:
1. blog-home.html 200 xhr angular.js 12587 4.6kb 21ms
2. all 200 xhr angular.js 12587 3.0kb 57ms
3. undefined pending xhr angular.js 12587 3.0kb 57ms 0kb
and the same when I go a blog category page. Ultimately they fail and kick the error above.
So before this gets voted down... I have read and tried here on stack:
No luck. Maybe I missed something or typed something wrong. I'm totally dumbfounded and I feel this is clearly above my skill level. So here is a bunch of code...
Server.js
var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var Mailgun = require('mailgun-js');
var path = require('path');
require('colors');
var app = express();
app.use(favicon(path.join(__dirname, 'client/assets/images', '*****')))
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({extended:true}))
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static("./bower_components"));
//app.all('/*', function(req, res, next) {
// res.sendFile('index.html', { root: 'client'});
//});
require('./server/config/mongoose.js');
var routes = require('./server/config/routes.js');
routes(app);
var api_key = '*********';
var domain = '*********';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: '********',
to: '********',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
app.listen(8000, function () {
console.log("I'm listening...".blue);
})
Index.html
<!DOCTYPE html>
<html lang="en" ng-app="Bridgeman">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<meta name="description" content="">
<meta name="author" content="">
<meta name="revisit-after" content="10 days">
<meta name="googlebot" content="noodp">
<meta name="msnbot" content="noodp">
<meta name="slurp" content="noodp, noydir">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ; connect-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; font-src * data:; frame-src https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d44591.890384371676!2d-118.36723983279781!3d33.83006153459027!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sus!4v1492366398808 ">
<meta content="/assets/images/******_BigBearSnowTrail.jpg" itemprop="image">
<link href="/assests/images/*******.ico" rel="shortcut icon">
<base href="/" />
<title></title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/modern-business.css" rel="stylesheet">
<link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="angular/angular.js"></script>
<script type="text/javascript" src="angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="/factories/ContactFactory.js"></script>
<script src="/factories/loginFactory.js"></script>
<script src="/factories/blogFactory.js"></script>
<script src="/controllers/contactController.js"></script>
<script src="/controllers/servicesController.js"></script>
<script src="/controllers/blogController.js"></script>
<script src="/controllers/blogViewController.js"></script>
<script src="/controllers/blogAWSController.js"></script>
<script src="/controllers/loginController.js"></script>
<base target="_blank">
</head>
<body>
<div ng-include='"templates/header.html"'></div>
<div ng-view=""></div>
<div ng-include='"templates/footer.html"'></div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
app.js (As you see I tried to seperate the AWS category into its own controller and both get's fired when that page loaded)
var Bridgeman = angular.module('Bridgeman', ['ngRoute']);
Bridgeman.config(['$routeProvider', '$httpProvider', '$locationProvider', '$qProvider', function($routeProvider, $httpProvider, $locationProvider, $qProvider){
$qProvider.errorOnUnhandledRejections(false);
$httpProvider.interceptors.push(function($q, $location){
return{
'responseError': function(rejection){
if(rejection.status == 401){
$location.url('/');
}
return $q.reject(rejection);
}
}
});
$routeProvider
.when('/', {
templateUrl:'partials/home.html',
}).when('/about', {
templateUrl:'partials/about.html',
}).when('/services', {
templateUrl: 'partials/services.html',
controller: 'servicesController'
}).when('/blog', {
templateUrl: 'partials/blog-home.html',
controller: 'blogViewController'
}).when('/blogAWS', {
templateUrl: 'partials/blog-aws.html',
controller: 'blogAWSController'
}).when('/blogSEO', {
templateUrl: 'partials/blog-SEO.html',
controller: 'blogViewController'
}).when('/blogSecurity', {
templateUrl: 'partials/blog-Security.html',
controller: 'blogViewController'
}).when('/blogBusiness', {
templateUrl: 'partials/blog-Business.html',
controller: 'blogViewController'
}).when('/blogSportsTech', {
templateUrl: 'partials/blog-SportsTech.html',
controller: 'blogViewController'
}).when('/blog-post/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'blogViewController'
}).when('/contact', {
templateUrl: 'partials/contact.html',
controller: 'contactController'
}).when('/login', {
templateUrl:'partials/login.html',
controller: 'loginController'
}).when('/admin', {
templateUrl:'partials/admin.html',
controller: 'blogController'
}).otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
}])
Bridgeman.run(function($rootScope, $location, $anchorScroll, $routeParams) {
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
})
blog-home.html (This is the main blog page which fires off both functions in my blogViewController)
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Blog Home
<small>My insights just for you</small>
</h1>
<ol class="breadcrumb">
<li>Home
</li>
<li class="active">Blog Home</li>
</ol>
</div>
</div>
<!-- /.row -->
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<div class="blogs" ng-repeat="b in blogs | orderBy:'-createdAt' | filter:searchblogs">
<!-- Blog Post -->
<h2>
<p>{{b.title}}</p>
</h2>
<p class="lead">
by {{b._user.name}} in the {{b.category}} category
</p>
<p><i class="fa fa-clock-o"></i> Posted on {{b.createdAt | date: "MMM. dd, yyyy"}}</p>
<hr>
<p>{{b.snippet}}</p>
<hr>
<p>{{b.content}}</p>
<a class="btn btn-primary" ng-href="/blog-post/{{b._id}}">Read More <i class="fa fa-angle-right"></i></a>
<hr>
</div>
<hr>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<!-- Blog Search Well -->
<div class="well">
<h4>Search my blogs</h4>
<div class="input-group">
<input type="text" class="form-control" ng-model="searchblogs">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
<!-- /.input-group -->
</div>
<!-- Blog Categories Well -->
<div class="well">
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<li>AWS
</li>
<li>SEO
</li>
<li>Security
</li>
<li>Business Tips
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<ul class="list-unstyled">
<li>Tech in Sports
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>My Blog</h4>
<p>Here is a collection of my genius (ha!) and tech insights. I'm sure sooner than later I will discuss Formula 1 tech but be assured there will be plenty of SEO and various web development tips/tools/tricks. And lets not forget some general business savviness I've learned over the years.</p>
</div>
</div>
</div>
<!-- /.row -->
blogViewController (where the functions are. Again, I commented out the getOneBlog and the error didn't happen. So what is triggering this fire and before the button is clicked?)
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
blogFactory.getAllBlogs(function(output){
$scope.blogs = output;
console.log(output);
})
blogFactory.getOneBlog($routeParams.id, function(output){
$scope.one = output;
console.log(output);
})
});
blogFactory (no issues here that I am aware of)
Bridgeman.factory('blogFactory', function($http){
var factory = {};
factory.submitNewBlog = function(input, callback){
$http.post('/blogs/new', input).then(function(output){
console.log("we just added a new blog");
callback(output.data);
});
}
//factory.submitNewComment = function(input, callback){
// $http.post('/comments/new', input).then(function(output){
// console.log("we just added a new comment");
// callback(output.data);
// });
//}
factory.getAllBlogs = function(callback){
$http.get('/blogs/all').then(function(output){
console.log("we just got all blogs");
callback(output.data);
});
}
factory.getOneBlog = function(blogID, callback){ //factory.getOneBlog = function(blogID, callback)
$http.get('/blogs/' + blogID).then(function (output){ //$http.get('blogs/' + blogID).then(function (output){
console.log(output.data); //callback(output.data);
console.log("we just got one blog");
callback(output.data);
});
}
return factory;
});
routes (a couple of different styles here just tying different formats to solve this)
var users = require('./../controllers/users.js');
var blogs = require('./../controllers/blogs.js');
module.exports = function(app){
app.post('/reg', function(req, res){
users.reg(req, res);
});
app.post('/login', function(req, res){
users.login(req, res);
});
app.get('/blogs/all', function(req, res) {
blogs.getAllBlogs(req, res);
});
app.get('/blogs/:id', blogs.getOneBlog); //app.get('/blogs/:id', blogs.getOneBlog)
app.post('/blogs/new', function(req, res) {
blogs.addBlog(req, res);
});
app.post('/contact', function(req,res){
var api_key = 'key-2451a2b90a87be616ab68b8f7c8f97ea';
var domain = 'sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'Website inquiry <postmaster#sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org>',
to: '*************com',
subject: req.body.full_name+" has sent you a message",
html:
req.body.full_name+" ..."+
req.body.phone+" ..."+
req.body.email+" ..."+
req.body.message
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
console.log("working...");
if(!error)
res.send("Your message has been sent");
else
res.send("Uh oh... something went wrong!");
});
});
}
blogs.js server side controller (no issue here... that I am aware of)
var Blog = mongoose.model('Blog');
module.exports = (function() {
return {
getAllBlogs: function(req, res){
Blog.find({}).populate([{path : '_user'}]).exec(function(err, b){
if(err){
console.log("there was an error when getting all blogs".red);
} else {
console.log(b);
console.log("successfully got all blogs".green);
res.json(b);
}
});
},
getOneBlog: function(req, res) {
console.log('Rich band aid');
if (req.params.id !== 'undefined') {
console.log('there was an id', req.params.id);
Blog.findOne({_id: req.params.id}).exec(function(err, b) { //({_id: req.params.id}, function(err,b){})
if(err){
console.log('error is', err);
console.log("there was an error when getting the blog".red);
} else {
console.log(b);
console.log("successfully got the blog".green);
res.json(b);
}
});
}else {
console.log('no id');
}
},
addBlog: function(req, res) {
console.log("===========================".yellow);
console.log(req.body);
console.log("===========================".yellow);
var b = new Blog({category: req.body.category, title: req.body.title, snippet: req.body.snippet, content: req.body.content, _user: req.body._user})
b.save(function(err){
if(err){
console.log("there was an error when saving a blog".red);
} else {
console.log(b);
console.log("successfully saved the above blog".green);
res.redirect('/blogs/all');
}
})
}
}
})();
and the mongoose db (no issue here... that I am aware of)
var mongoose = require('mongoose');
// Create the message schema
var BlogSchema = new mongoose.Schema({
category: {type: String, required: true, minlength: 3, enum:['Security', 'Business', 'SEO', 'AWS', 'Tech in Sports']},
title: {type: String, required: true, minlength: 3},
snippet: {type: String, required: true, minlength: 3},
content: {type: String, required: true, minlength: 3},
_user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
}, {timestamps: true});
mongoose.model('Blog', BlogSchema);
Any help is greatly appreciated. Thanks
PS... and yes I am aware of the CPS error for the frame-src and the font-src when you try to refresh the page. Super annoying.
Was able to figure it out with a friend. Problem solved by wrapping the 2 functions into an 'if' statement. It may not be the proper solution but it works perfectly.
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
if ($routeParams.id) {
blogFactory.getOneBlog($routeParams.id, function(output) {
$scope.one = output;
console.log(output);
});
} else {
blogFactory.getAllBlogs(function(output) {
$scope.blogs = output;
console.log(output);
});
}
});
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i have project of login page for admin redirect to dashboard. it use expressjs as a server side and angularjs as a client side.
this client side login page use angularjs
//this is the angular controller that use for get the data from login form
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
$http.post('/admin/',{useremail:userEmail, userpassword:userPassword});
}
})
})();
this is the login page html
<!DOCTYPE html>
<html lang="en" >
<head>
<title>Awi Admin</title>
<meta charset="utf-8">
<meta name="description" content="Aplikasi AWI Realtime Lelang Menggunakan Framework ExpressJS dan Realtime Database Firebase">
<meta name="author" content="Muhammad Abubakar Siddiq - MAS Abbe">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel='stylesheet' href='/stylesheets/login.css'/>
<link rel="stylesheet" type="text/css" href="/stylesheets/font-awesome.min.css">>
</head>
<body ng-app="myAdmin">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="btn_avatar">
<img src="/images/avatar.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<h3 class="text-center">Welcome Admin Lelang</h3>
<form name="login-form" role="form" ng-controller="loginCtrl" novalidate>
<div class="fields">
<input type="text" class="input" placeholder="Username" ng-model="user.email" required/>
<span style="color:red" ng-show="login-form.email.$dirty && login-form.user.$invalid">
<span ng-show="login-form.email.$error.required">Username is required.</span>
</span>
</div>
<div class="fields">
<input type="password" class="input" required-pattern=.*\S.* placeholder="password" ng-model="user.password"/>
<span style="color:red" ng-show="login-form.password.$dirty && login-form.user.$invalid">
<span ng-show="login-form.password.$error.required">Password is required.</span>
</span>
</div>
<div class="alert alert-warning" ng-show="login-form.email.$error.email">
<em class="fa fa-lg fa-warning"> </em>Peringatan, username atau password salah
</div>
<div class="profile__footer">
<center>
<button class="btn" id="btn-submit" ng-click="login()">LOG IN</button>
</center>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.getElementById('btn_avatar').addEventListener('click',
function () {
[].map.call(document.querySelectorAll('.profile'),
function(el) {
el.classList.toggle('profile--open');
});
}
);
</script>
<script type="text/javascript" src = "/javascripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src = "/javascripts/bootstraps/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular-resource.min.js"></script>
<script type="text/javascript" src = "/javascripts/login.js"></script>//==> this is the function for login that call the angular controller
</body>
</html>
and this index.js as server side expressjs
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const app = express();
const firebaseApp = admin.initializeApp(
functions.config().admin
);
const HTTP_SERVER_ERROR = 500;
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
app.get('/admin/', (req, res)=>{
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
res.render('index')
});
//this is the functions post for server side express
app.post('/admin/', (req, res)=>{
console.log('post login'+req.body.userEmail, req.body.userPassword);
admin.auth().signInWithEmailAndPassword(req.body.userEmail, req.body.userPassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
exports.app = functions.https.onRequest(app);
this my project in github project
my issue for this project is the data from the post function of angular controller to the expressjs post rendering detected as unidentified.
can anyone enlight me what is the cause?? and how to solved this.
this function is naver get to run firebase auth() functions
Try as,
$http({
method: 'POST',
url: '//admin/',
data: {useremail:userEmail, userpassword:userPassword}
}).then(function(rsp){...});
this is the angular controller
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
var myObject = {useremail:userEmail, userpassword:userPassword}
$http({
method: 'POST',
url : '/admin/',
data : JSON.stringify(myObject)
});
}
})
})();
this is the expressjs functions
app.post('/admin/', (req, res)=>{
console.log("####Success");
console.log('post login '+req.body.useremail, req.body.userpassword);
admin.auth().signInWithEmailAndPassword(req.body.useremail, req.body.userpassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
after remote desktop consult, final fixed
[Update] I've found the site works with Microsoft Edge just fine. IE seems to be the only one having issues.
So I've run into an issue where my site fails to load in Internet Explorer and throws this error:
[$injector:modulerr] Failed to instantiate module necs due to:
Error: [$injector:modulerr] Failed to instantiate module necs.LandingModule.controller due to:
Error: [$injector:nomod] Module 'necs.LandingModule.controller' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument
The site loads completely fine in both Firefox and Chrome, but refuses to load in Internet Explorer. I'm not sure what the issue could be as the 'necs.LandingModule.controller' is both spelled correctly and loaded. I've tried removing some of the code within the Controller to see if it would load, hoping that I could find exactly which piece of code IE doesn't like, but I've yet to be successful in doing that.
Let me know if you need more information and I will provide as needed.
CONTROLLER.JS
angular.module('necs.LandingModule.controller', [
'necs.FeaturedItemsModule.directives'])
.controller('LandingController', ['$scope', '$location', '$routeParams', '$window', 'ajaxUtil',
function($scope, $location, $routeParams, $window, ajaxUtil){
$scope.landingProducts = [1,2,3,4,5,6];
$scope.getFeaturedProducts = function() {
ajaxUtil.get('/api/landingProducts', $scope, 'onGetFeaturedProducts');
};
$scope.onGetFeaturedProducts = function(response) {
if (response) {
$scope.landingProducts = response.data;
}
};
$scope.getCatalogMailer = function(id){
if (id == 'link1'){
$window.open("link");
}else if(id == 'link2'){
$location.url('link');
}else if(id =='link3'){
$location.url('link');
}else if(id =='link4'){
$location.url('link');
}else if(id =='link5'){
$location.url('link');
}
};
$scope.getFeaturedProducts();
ga('send', 'pageview', {
'title': 'landing page'
});
}]);
INDEX.HTML
<!DOCTYPE html>
<html lang="en" ng-app="necs">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0">
<title>NECS</title>
<link rel="icon" type="image/png" href="assets/images/icon.png" sizes="32x32" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/css/app.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:300,400,700' rel='stylesheet' type='text/css'>
<script src="/bower_components/angular/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
<script src="/bower_components/angular-route/angular-route.js"></script>
<script src="/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="/bower_components/angular-strap/dist/angular-strap.min.js"></script>
<script src="/bower_components/angular-strap/dist/angular-strap.tpl.min.js"></script>
<script src="/bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controllers.js"></script>
<script src="/js/directives.js"></script>
<script src="/js/services.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67702514-1', {
'cookieDomain': 'none'
});
</script>
<base href="/" />
</head>
<body data-spy="scroll" data-offset="15">
<div class="container">
<header-directive></header-directive>
<div ng-view >
</div>
</div>
<div class="main-footer">
<div class="container">
<footer-directive></footer-directive>
</div>
</div>
</body>
</html>
LANDING.HTML
<div class="landing row">
<div class="row">
<div class="col-xs-12">
<div class="well">
<custom-order-directive></custom-order-directive>
<featured-items-directive></featured-items-directive>
</div>
</div>
</div>
<div class="row">
<div ng-repeat="item in landingProducts" class="col-sm-12 col-md-4">
<div class="thumbnail main-container">
<div class="image-container">
<!--<img ng-click="onProductClick(item.id)" class="top-sellers" ng-src="{{item.img}}" />-->
<img ng-src="{{item.image}}" />
</div>
<div class="caption text-center landinglinks">
<h3 >{{item.header}}</h3>
<!--<p ng-bind-html="item.text" ng-click="onProductClick(item.link)"></p>-->
<p ng-bind-html="item.text" ng-click="getCatalogMailer(item.link)"></p>
</div>
</div>
</div>
</div>
FRONT APP.JS
angular.module('necs', ['ngRoute',
'necs.LandingModule.controller',
'necs.CustomModeModule.controller',
'necs.CustomOrderModule.controller',
'necs.CustomPdfModule.controller',
'necs.CatalogModule.controller',
'necs.ProductModule.controller',
'necs.HeaderModule.directives',
'necs.FooterModule.directives',
'necs.MenuModule.directives',
'necs.DownloadsModule.controller',
'necs.InformationModule.controller',
'necs.LoginModule.controller',
'necs.AccountModule.controller',
'necs.AdministrationModule.controller',
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'html/landing.html',
controller: 'LandingController'
})
.when('/customMode', {
templateUrl: 'html/customMode.html',
controller: 'CustomModeController'
})
.when('/customOrder', {
templateUrl: 'html/customOrder.html',
controller: 'CustomOrderController'
})
.when('/customPdf', {
templateUrl: 'html/customPdf.html',
controller: 'CustomPdfController'
})
.when('/catalog', {
templateUrl:'html/catalog.html',
controller: 'CatalogController'
})
.when('/catalog/product', {
templateUrl: 'html/product.html',
controller: 'ProductController'
})
.when('/downloads', {
templateUrl: 'html/downloads.html',
controller: 'DownloadsController'
})
.when('/information', {
templateUrl: 'html/information.html',
controller: 'InformationController'
})
.when('/cart', {
templateUrl: 'html/cart.html',
controller: 'CartController'
})
.when('/login', {
templateUrl: 'html/login.html',
controller: 'LoginController'
})
.when('/account', {
templateUrl: 'html/account.html',
controller: 'AccountController'
})
.when('/administration', {
templateUrl: 'html/administration.html',
controller: 'AdministrationController'
})
.otherwise({
redirectTo: '/'
});
}]);
SERVER APP.JS
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var session = require('express-session');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var nodemailer = require('nodemailer');
var exphbs = require('express-handlebars');
var hbs = require('nodemailer-express-handlebars');
var db = require('./db')();
var user = require('./user')();
var fs = require('fs');
var Cookies = require('cookies');
var Product = require('./product');
var Category = require('./category');
var Download = require('./download');
var Codes = require('./codes');
var Specsheet = require('./specsheet');
var app = express();
app.use(express.static(path.resolve(__dirname + '/../front/static')));
app.use(bodyParser.urlencoded({limit: '50mb'}));
app.use(bodyParser.json({limit: '50mb'}));
app.get('/qr/:qrcode', function (req, res) {
var domain = 'domain.com/#/qr/';
var qrcode = req.params.qrcode;
res.redirect(domain+qrcode);
});
//login
app.use(flash());
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// parse application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(80);
var config = {
"USER": "user",
"PASS": "password",
"HOST": "127.0.0.1",
"PORT": "22222",
"DATABASE" : "database"
};
var dbPath = "mongodb://" + config.USER + ":"+ config.PASS + "#"+ config.HOST + ":"+ config.PORT + "/"+ config.DATABASE;
mongoose.connect(dbPath);
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('connected successfully');
});
//landing products
app.get('/api/landingProducts',function(req,res) {
var landingItems = {
landing1: {
image: "/assets/images/landing1.jpg",
text: "text1",
header: "header1",
link: "link1"
},
landing2: {
image: "/assets/images/landing2.jpg",
text: "text2",
header: "header2",
link: "link2"
},
landing3: {
image: "/assets/images/landing3.jpg",
text: "text3",
header: "header3",
link: "link3"
},
landing4: {
image: "/assets/images/landing4.jpg",
text: "text4",
header: "header4",
link: "link4"
},
landing5: {
image: "/assets/images/landing5.jpg",
text: 'text5',
header: "header5",
link: "link5"
},
landing6: {
image: "/assets/images/landing6.jpg",
text: "text6",
header: "header6",
link: "link5"
}
};
res.send(landingItems);
});
I tested on IE 11:
This is what I am getting: Expected ':' in controllers.js (1551,3)
It looks like you have declared 3 additional variables, but not properly:
$scope.getWidthDropdown = {
warr
};
And there are two others.
You should change that to
$scope.getWidhtDropdown = {
warr: warr
};
I am not sure if that will fix the issue though. Could be a red herring
i'm learning MEAN stack, and trying to build an app based on demoof this course (thinkster.io/mean-stack-tutorial#creating-schemas-with-mongoose).
I checked that's there is on db with curl, it's ok, but angular dont bind them.
--> This is the view (index.ejs) :
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="javascripts/angularApp.js"></script>
</head>
<body ng-app="demo">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Patients : </h1>
</div>
<div ng-repeat="patient in patients">
<a>{{patient.name}} - Nom: {{patient.surname}} - Age: {{patient.old}}</a>
</div>
</script>
</body>
</html>
--> This is my node js code (index.js)
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Patient = mongoose.model('Patient');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET all patients */
router.get('/patients', function(req, res, next){
Patient.find(function(err, patients){
if(err){ return next(err); }
res.json(patients);
});
});
//configure express : retrieve automatically post by id
router.param('patient', function(req, res, next, id){
var query = Patient.findById(id);
query.exec(function(err, patient){
if(err){ return next(err); }
if(!patient){ return next(new Error("Aucun patient dans la base...")); }
req.patient = patient;
return next();
});
});
module.exports = router;
--> And this is my angular code (angularApp.js)
var app = angular.module('flapperNews', ['ui.router']);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
app.factory('posts', ['$http', function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
}]);
You didn't bind the controller "MainCtrl" in your html
This issues seems like a very common one. But I have been unsuccessful to find the issue for a long time now. I have distributed the application, controller,service modules into separate js files as below.
app.js
/** Main AngularJS Web Application */
var app = angular.module('ngdemo', [ 'ngdemo.controllers', 'ngdemo.services' ]);
app
.config([
'$routeProvider',
'$httpProvider',
function($routeProvider, $httpProvider) {
$routeProvider.when('/documents', {
templateUrl : 'documents.html',
controller : 'documentListCtrl'
}).when('/documents/:id', {
templateUrl : 'edit_document.html',
controller : 'documentDetailCtrl'
}).when('/document', {
templateUrl : 'create_document.html',
controller : 'documentCreationCtrl'
}).otherwise({
redirectTo : '/home'
});
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
} ]);
and document_controllers.js
var controllers = angular.module('ngdemo.controllers', []);
/* ... */
controllers.controller( 'navigation', ['$rootScope', '$scope', '$http', '$location', '$route', function($rootScope, $scope, $http, $location, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}).error(function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/documents");
$scope.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/home");
$scope.error = true;
$rootScope.authenticated = false;
}
})
};
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}]);
/* ... */
controllers.controller('documentListCtrl', ['$scope', 'DocumentsFactory', 'DocumentFactory', '$location',
function ($scope, DocumentsFactory, DocumentFactory, $location) {
// callback for ng-click 'editDocument':
$scope.editDocument = function (documentId) {
$location.path('/documents/' + documentId);
};
// callback for ng-click 'deleteDocument':
$scope.deleteDocument = function (userId) {
DocumentFactory.delete({ id: userId });
$scope.documents = DocumentsFactory.query();
};
// callback for ng-click 'createDocument':
$scope.createNewDocument = function () {
$location.path('/document');
};
$scope.documents = DocumentsFactory.query();
}]);
/* ... */
controllers.controller('documentDetailCtrl', ['$scope', '$routeParams', 'DocumentFactory', '$location',
function ($scope, $routeParams, DocumentFactory, $location) {
// callback for ng-click 'updateDocument':
$scope.updateDocument = function () {
DocumentFactory.update($scope.document);
$location.path('/documents');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/documents');
};
$scope.document = DocumentFactory.show({id: $routeParams.id});
}]);
/* ... */
controllers.controller('documentCreationCtrl', ['$scope', 'DocumentsFactory', '$location',
function ($scope, DocumentsFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewDocument = function () {
DocumentsFactory.create($scope.document);
$location.path('/documents');
}
}]);
and finally document_services.js
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('DocumentsFactory', function ($resource) {
return $resource('/rest/documents', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
services.factory('DocumentFactory', function ($resource) {
return $resource('/rest/documents/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
})
});
In my index.html file,
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Sample Project</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/jumbotron.css" rel="stylesheet">
</head>
<body ng-app="ngdemo" class="ng-cloak">
<nav class="navbar navbar-inverse navbar-fixed-top">
<!-- ng-controller="navigation" -->
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ng-class="{active:tab('home')}">Home</li>
<li ng-show="authenticated" ng-class="{active:tab('document')}">Document</li>
</ul>
<form ng-show="!authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" id="username"
name="username" ng-model="credentials.username" />
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" ng-model="credentials.password" />
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
<div ng-show="authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<button type="submit" class="btn btn-success" ng-click="logout()">Log
Out</button>
</div>
</div>
</div>
</nav>
<div ng-view class="container"></div>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/app.js"></script>
<script src="js/document_controllers.js"></script>
<script src="js/document_services.js"></script>
</body>
</html>
In my project I am using wro4j-maven-plugin to generate javaScript files
<groups xmlns="http://www.isdc.ro/wro">
<group name="angular-bootstrap">
<css>webjar:bootstrap/3.2.0/less/bootstrap.less</css>
<css>file:${project.basedir}/src/main/wro/main.less</css>
<js>webjar:jquery/2.1.1/jquery.min.js</js>
<js>webjar:angularjs/1.3.8/angular.min.js</js>
<js>webjar:angularjs/1.3.8/angular-route.min.js</js>
<js>webjar:angularjs/1.3.8/angular-cookies.min.js</js>
</group>
</groups>
So, this generated angular-bootstrapfile is properly referenced in the html file, but still the loading of modules seems to be failing. Any help is immensely appreciated.
Thanks
You probably need to install the route provider and include ngRoute dependancy in your app.js.
Here is the documentation: $routeProvider
And about the installation: ngRoute
I am having an issue with AngularJS where a function from one of my services (authService.isLoggedIn()) is throwing 'not a function' exception in my console. But it only happens after a route change occurs (like after logging in), so before a route change has occured the function is successfully called from within my $routeChangeStart event handler, but after a route change has occured, i receive this exception in my console:
TypeError: authService.isLoggedIn is not a function
at app.config.js:13
If I need to post my server side code (NodeJS + Express for API routing), let me know.
Here is my index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="stylesheet.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<base href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<div ng-controller="navCtrl">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">TriviaAttack!</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a ng-click="showLogin()">Login</a></li>
<li><a ng-click="showRegister()">Register</a></li>
</ul>
</div>
</div>
</nav>
<div ng-view></div>
</div>
<script src="./js/ui-bootstrap-custom-tpls-0.14.0.min.js"></script>
<script src="./app/app.js"></script>
<script src="./app/app.routes.js"></script>
<script src="./app/app.config.js"></script>
<script src="./app/services/authInterceptor.js"></script>
<script src="./app/services/auth.js"></script>
<script src="./app/services/authToken.js"></script>
<script src="./app/services/user.js"></script>
<script src="./app/controllers/nav.js"></script>
<script src="./app/controllers/home.js"></script>
<script src="./app/controllers/login.js"></script>
<script src="./app/controllers/landingpage.js"></script>
</body>
</html>
app.js
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
console.log('myApp loaded');
app.routes.js
angular.module('myApp')
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'landingpageCtrl'
})
.when('/home', {
templateUrl: './app/views/home.html',
controller: 'homeCtrl'
});
});
console.log('app.route loaded');
app.config.js
angular.module('myApp')
.config(function($locationProvider, $httpProvider) {
//Removes # from urls.
$locationProvider.html5Mode(true);
//Add authentication interceptor to $httpProvider.interceptors array.
$httpProvider.interceptors.push('authInterceptor');
})
.run(function($rootScope, authService, $location) {
$rootScope.$on('$routeChangeStart', function(event) {
authService.isLoggedIn()
.then(function(response) {
console.log(response);
if (response.status == 200) {
$rootScope.user = response.data;
} else {
console.log('User not authenticated/logged in.');
}
});
});
});
services/authInterceptor.js
angular.module('myApp').
service('authInterceptor', function($location, authToken) {
var service = this;
service.request = function(config) {
config.headers.authorization = authToken.getToken();
return config;
}
service.responseError = function(response) {
$location.path('/');
return response;
}
});
services/auth.js
angular.module('myApp')
.service('authService', function($http) {
var service = this;
service.login = function(user, pass) {
return $http.post('/api/login', {username: user, password: pass});
}
service.isLoggedIn = function() {
return $http.get('/api/user');
}
});
controllers/login.js
angular.module('myApp')
.controller('loginCtrl', function($scope, $modalInstance, $location, authService, authToken) {
$scope.msg = '';
$scope.loginData = {
username: '',
password: ''
}
$scope.login = function() {
authService.login($scope.loginData.username, $scope.loginData.password)
.then(function(response) {
if (response.data.success) {
authToken.setToken(response.data.token);
authService.isLoggedIn = true;
$modalInstance.close();
$location.path('/home');
} else {
$scope.msg = response.data.message;
console.log('error logging in');
}
});
$scope.loginData = {};
};
});
In your controllers/login.js
You are setting
authServer.isLoggedIn to true
That is making it a "boolean" right?