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;
Related
I have developed web app using angularjs single page application.Now I am building my own web server using nodejs.
The index page is visible when page is loaded but on navigation to other pages.
The get request goes on infinite loop with 304 status.
**Please note I need css and javascript for bootstrap and jquery.**When these are loaded I receive the error.I have inserted app.js(server config),index.js(nodejs routing config),moduleapp.js(angularjs routing config) and picture of error.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/home", {
templateUrl : "/views/home.hbs",
controller : "homeCtrl"
})
.when("/aboutme",{
templateUrl:"/views/aboutme.hbs",
controller:"aboutCtrl"
})
.when("/education", {
templateUrl : "/views/education.hbs",
controller : "eduCtrl"
})
.when("/interest",{
templateUrl:"/views/interest.hbs",
controller:"interestCtrl"
})
.when("/gallery",{
templateUrl:"/views/gallery.hbs",
controller:"galleryCtrl"
})
.when("/contact", {
templateUrl : "/views/contact.hbs",
controller : "contactCtrl"
});
});
app.controller("homeCtrl", function ($scope) {
$scope.msg = "Welcome to homepage";
});
app.controller("aboutCtrl", function ($scope) {
$scope.msg = "About me";
});
app.controller("eduCtrl", function ($scope) {
$scope.msg = "Hi Academics";
});
app.controller("interestCtrl", function ($scope) {
$scope.msg = "My interests";
});
app.controller("galleryCtrl",function($scope){
$scope.msg="My photos";
})
app.controller("contactCtrl", function ($scope) {
$scope.msg = "Contact me";
});
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('layout');
});
router.get('/:name', function(req, res, next) {
var name=req.params.name;
res.render(name);
});
module.exports = router;
<!-- end snippet -->
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 hbs=require('express-handlebars');
var index = require('./routes/index');
var app = express();
// view engine setup
app.engine('hbs',hbs({extname:'hbs'}))
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// 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('/', index);
app.use('*', index);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I'm trying to implement html5mode(true) for my angular app on my Node/Express server.
I'm getting the dreaded "cannot /GET" error when I try to reload.
The fix that I see being implemented for this on the server is by adding a catch all get request in the express app.js.
I've done that, but It's not working for me.
Here is my code where I add the catch all at the bottom, but when I reload, I get the following message: Error: "ENOENT: no such file or directory, stat '/Users/christophernakea/Documents/Projects/express4/testproj/server/client/app/index.html' at Error (native)"
That's clearly not what I'm calling below.
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 mongoose = require('mongoose');
var cors = require('cors');
mongoose.connect('mongodb://localhost/test');
var app = express();
// 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: true }));
app.use(cookieParser());
app.use(cors());
app.use('/api', require('./routes/api'));
app.use('/sendmail', require('./routes/sendmail'));
app.use(express.static(path.join(__dirname, '../client/app/custom')));
app.use(express.static(path.join(__dirname, '/dist')));
// 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.all('/*', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});
module.exports = app;
My angular module has the standard...
'use strict';
angular
.module('clientApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ui.router',
'ngSanitize',
'ngTouch',
'xeditable'
])
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
$urlRouterProvider.otherwise("/");
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainController'
});
}])
I am making an angularjs app,in which i am using Express as backend.The problem i'm facing is not being able to switch between my Html pages.Kindly help,i have tried a lot of tutorials but none of them worked.I guess there must be some problem in the path i am providing.
Here is my server.js
`
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var ejs = require('ejs');
var urlencodedParser = bodyParser.urlencoded({extended:false});
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
connection.connect();
app.use(express.static('public'));
//app.set('views', __dirname + 'views');//this is used because res.render('../template/goto_page_options.html', {values : city});
//was not able to render the view
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.get('/', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('../template/login.html'));
console.log("WOW");
})
app.get('/home', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('../template/home.html'));
console.log("home requested");
})
`
This is my app.js
app.config(['$routeProvider', function ($routeProvider){
$routeProvider
.when('/',{
redirectTo: '/login'
})
.when('/home',{
templateUrl:'home.html'
})
.when('/employee',{
templateUrl:'employee.html'
})
.when('/login',{
templateUrl:'login.html'
})
.otherwise({ redirectTo: '/login' });
}]);
This is my index.html
<body ng-app="starter">
<div ng-view></div>
<script src="http://localhost/try/www/js/app.js"></script>
<script src="http://localhost/try/www/js/server.js"></script>
</body>
my directory structure is
templates
--login.html
--home.hml
js
--app.js
index.html
In your index.html, you have included
<script src="http://localhost/try/www/js/server.js"></script>
But in your directory structure, there is no such file.Check the console in your browser. There will be file not found error.
Also there is no such file
employee.html
login.html
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 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.