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
Related
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 display list of the products; once clicked on the product row, the full screen detail view is displayed for it. I am using ui-router for front end routing to to get from list view to detail view. Example of the address url: http://localhost:3000/detail/product1 .
If I enter this url into browser address, it does not redirect to that product detail, instead it tries to load index.html since it is the default page in nodejs. How can I redirect to ui-router state in node.js?
Angular App.js
'use strict';
/* App Module */
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
function($stateProvider, $urlRouterProvider,$locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'partials/listView.html'
})
.state('list', {
url: '/',
templateUrl: 'partials/listView.html'
})
.state('detail', {
url: '/detail/:key',
params: {
key: { value: "" }
},
templateUrl: 'partials/detailView.html',
controller: 'DetailController'
})
// use the HTML5 History API
$locationProvider.html5Mode(true);
}]);
nodeJS app.js:
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path')
, bodyParser = require("body-parser");
var app = express();
app.set('port', process.env.PORT || 80);
//front end views are in /public folder; using html for views
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
//parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
//using index.html as starting point
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(app.router);
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index); //redirect to index.html on page load
app.get('/detail/*', function(req, res){
var urlSegments = req.url.split('/',3);
var key=urlSegments[2]; // product id
// ??? How can I redirect to detail state in angular ui-router here passing the key of the product ???
});
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Thank you
The issue was fixed when state was changed to use query in url as:
.state('detail', {
url: '/detail?key',
params: {
key: { value: "" }
},
templateUrl: 'partials/detailView.html',
controller: 'DetailController'
})
I want to integrate angular routing into my node app, but I'm getting an error and not sure how to resolve it. I just want to have a link to redirects to an about.html file, that is inside a directory called public.
In my index.html file I have a link:
About
In my server.js I have this:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);
In my js file I have the $routeProvider set up as follows:
myApp.config(function($routeProvider){
$routeProvider
.when('/about',{
templateUrl: '/about.html'
});
});
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;
I have a web application that uses OAuth 2 running on Node. Using EJS templates I was able to properly create a workflow that prompts a user to login, authenticate, and then performs a "GetUser" GET command and dumps the output to the screen. Recently I have attempted to remove EJS and want to get AnguarJS working.
Currently I have removed EJS and implemented Angular, however with angular many strange things happen and I cannot figure out why!
When my user clicks "Login" they are supposed to be brought to another website that they login to using OAuth 2. This process works fine on Node with EJS, however with angular my controller loads, the correct partial is loaded but there is no data. Reviewing this process with Chrome DEV tools I see the following error
XMLHttpRequest cannot load http://website/oauth/authorize?...
No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
What is even weirder is that in the network tab I can see the correct Request URL! If I copy and paste this URL into another tab my "GetUser" command executes, but then node crashes and my page fails.
I have attempted different browsers, enabling CORS, and configuring CORS. I know the issue is with Angular as I can successfully use the same code with EJS. I have put my Angular code below, any assistance would be appreciated!
Server Side
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 config = require('./config.js')
var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
var session = require('express-session');
var index = require('./routes/index');
var login = require('./routes/login');
var logout = require('./routes/logout');
passport.serializeUser(function(user, done) {done(null, user);
});
passport.deserializeUser(function(obj, done) {done(null, obj);
});
// config
passport.use('Company', new OAuth2Strategy({
authorizationURL: config.authorizationURL,
tokenURL: config.tokenURL,
clientID: config.clientID,
clientSecret: config.clientSecret,
callbackURL: config.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
process.nextTick(function () {
// store access token
req.session.accessToken=accessToken;
return done(null, profile);
});
}
));
var app = express();
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(session({secret: 'secret'}))
app.use(passport.initialize());
app.use(passport.session());
// configure Express
app.get('/api/login', ensureAuthenticated, login.execute);
app.get('/api/logout', logout.execute);
app.get('/auth/company',
passport.authenticate('company'),
function(req, res){
});
app.get('/auth/company/callback',
passport.authenticate('company', { failureRedirect: '/' }),
function(req, res) {
console.log('comming back from company');
res.redirect('/api/login');
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/')
}
module.exports = app;
Login.js (Route)
var request = require('request');
exports.execute = function (req, res) {
console.log(req.user);
console.log(req.app.get('accessToken'));
var accessToken = req.session.accessToken;
console.log("accessToken in loginjs" + accessToken);
if(accessToken){
var options = {
url: 'http://company/getCurrentUser',
headers: {
Authorization: 'bearer ' + accessToken
}
};
request.get(options, function(error, response, body){
if(error){
console.log('login.js inside error' + error);
res.json('login.js inside error' + error);
return;
}
console.log(response);
res.render('account', { user: response });
});
}else{
res.render('account', { user: req.user });
}
}
www
var debug = require('debug')('myApp');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Client Side
app.js (angular)##
angular.module('MyApp', ['ngCookies', 'ngResource', 'ngMessages', 'ngRoute', 'mgcrea.ngStrap'])
.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/account.html',
controller: 'LoginCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
login.js Controller
angular.module('MyApp')
.controller('LoginCtrl', ['$scope', 'Auth', function($scope, Auth){
var user = Auth.authorize();
$scope.user=user;
$scope.headingTitle='Logged in page';
}]);
auth.js Service
angular.module('MyApp')
.factory('Auth', ['$resource', function($resource){
return $resource('/auth/company', null,
{
'authorize': {method: 'GET'}
});
}]);
home.html Partial to route to company Oauth2
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<p>Login via Company</p>
</div>
</div>
</div>
</div>
account.html Partial to show User data
<div>
<h1>You are logged in.</h1>
Go home<br>
Logout<br>
<p>Dumping User: {{user}}</p>
</div>
edit
I have tried the follow with no success
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X- Requested-With, Access-Control-Allow-Origin');
res.header("Access-Control-Max-Age", "86400"); // 24 hours
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
var app = express();
app.use(allowCrossDomain);
Edit 2:
I did some more digging and also noticed that Angular is not listed as initiating the second URL. Its almost as if angular is re-routing the callback URL as a separate call of its own. I have attached the below picture
Edit 3:
I have continued to work on this but cannot figure out why Angular is stripping out my headers! Any Additional input would be greatly appreciated!
Edit 4:
I found that I can have the webpage load the route instead of Angular by adding the code below to the Login button. After doing this and pointing the link to /auth/company rather than to api/login I get successfully redirected to the login page!
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<p><a target="_self" href="/auth/company">Login via Company</a></p>
</div>
</div>
</div>
</div>
However the battle continues, as after I login I get redirected to the below picture - inside of node I receive the data however the application dies and does not show the /account page.
Can you try enabling CORS in express server
npm install cors
app.js
var cors = require('cors')
var app = express()
app.use(cors())
Reference to this link
I never user $resource and instead use $http. You have to enable 'withCredentials' on the client's request as well. I also think you DON'T need if('OPTIONS' == req.method) as I've never needed this. One more note, you can't use a wildcard domain '*' with credentials. You'd have to explicitly allow origin 'http://127.0.0.1:8080' and make sure you're cookie uses the 127 and not localhost (you'll run into problems with cookies otherwise).
var req = {
method:'POST',
url: 'users/login',
data: {
},
withCredentials:true
};
$http(req).then(function (response) {
if( response.data.success ){
}
if( response.data.error){
}
});