Hello evryone I have a single page app. The problem is that for one page it doesn't display the partial.
Here is my 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 session = require('express-session');
var passport = require('passport');
//initialize mongoose schemas
require('./models/models');
var index = require('./routes/index');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
var mongoose = require('mongoose'); //add for Mongo support
mongoose.connect('mongodb://localhost/test-chirp'); //connect to Mongo
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(session({
secret: 'keyboard cat'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', index);
app.use('/auth', authenticate);
app.use('/api', api);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
// 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;
my angular controler :
var app = angular.module('chirpApp', ['ngRoute']).run(function($rootScope, $http){
$rootScope.authenticated = false;
$rootScope.current_user = "";
$rootScope.logout = function(){
$http.get('/auth/signout');
$rootScope.authenticated = false;
$rootScope.current_user = "";
};
});
app.config(function($routeProvider){
$routeProvider
//the timeline display
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
//the login display
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
//the signup display
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
});
});
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
app.controller('authController', function($scope, $rootScope, $http, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
});
};
});
my main html page
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container">
<nav class="navbar-fluid navbar-default navbar-fixed-top">
<div class="container">
<a class="navbar-brand" href="#"> Chirp! </a>
<p class="navbar-text"> Learn the MEAN stack by building this tiny app</p>
<p class="navbar-right navbar-text" ng-hide="authenticated">Login or Register</p>
<p class="navbar-right navbar-text" ng-show="authenticated">Logout</p>
<p class="navbar-right navbar-text" ng-show="authenticated">Signed in as {{current_user}}</p>
</div>
</nav>
<div class="col-md-offset-2 col-md-8">
<div ng-view>
</div>
</div>
</div>
</body>
</html>
And my partial
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
</form>
Please help i will provide more code on demand
Related
Note: I tried all questions & answer related to this topic but am not able to resolve the issue.
I want to base path from Node Js Side. Example below. I using [angular js + NodeJS/ExpressJS ]
<base href="/Tutorial/Routing/StateProvider/" />
html
<!DOCTYPE html>
<html ng-app="myapp2">
<title>Index | Angular Js</title>
<base href="/Tutorial/Routing/StateProvider/" />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
<script src="StateProviderController.js"></script>
<body >
<nav class="navbar navbar-default row">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" ui-sref="TutorialHome"> State Routing</a>
</div>
<ul class="nav navbar-nav">
<li><a ui-sref="Profile">Profile</a></li><!--State Transition on click-->
<li><a ui-sref="Account">Account</a></li><!--State Transition on click-->
<li><a ui-sref="Setting">Setting</a></li><!--State Transition on click-->
<li style="float: right;"><a ui-sref="Home">Home</a></li><!--State Transition on click-->
</ul>
</div>
</nav>
Controller Js
var myapp= angular.module('myapp2',["ui.router"]);
myapp.config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvider){
$urlMatcherFactoryProvider.strictMode(false);
$stateProvider
.state('TutorialHome', {
url:'/index',
templateUrl:'/index.html'
})
.state('Home',{
url:'/',
templateUrl:'http://localhost:3000/'
})
.state('Profile',{
url:'/Profile',
templateUrl:'Profile.html'
})
.state('Account',{
url:'/Account',
templateUrl:'Account.html'
})
.state('Setting',{
url:'/Setting',
templateUrl:'Setting.html'
})
.state('Setting.StudenListing', {
url:'/StudenList',
views: {
'StudenListing': {
templateUrl: 'StudenListing.html',
controller:'StudentListingData'
}
}
})
.state('Setting.StudenListing.StudentList',{
url:'/StudenList/:StudentID',
/* templateUrl: 'StudentDetails.html',
controller:'StudentDetails'*/
views:{
'StudentDetails': {
templateUrl: 'StudentDetails.html',
controller:'StudentDetails'
}
}
})
;
// $urlRouterProvider.otherwise('/index');
$locationProvider.html5Mode(true);
});
myapp.controller('StateProviderCtrl',function($scope){
$scope.message ="Welcome To State Provider Page";
});
myapp.controller('StudentListingData',function($scope,$http){
console.log('test');
$http.get('/StudenRecordData').success(function(response){
// console.log(response);
$scope.StudentRecorddata =response;
})
});
myapp.controller('StudentDetails',function($scope,$http,$stateParams){
$scope.StudentID = $stateParams.StudentID;
//console.log( $scope.StudentID);
$http.get('/StuentRecordSearch/'+ $stateParams.StudentID).success(function(response){
//console.log(response);
$scope.StuentDetails =response[0];
})
});
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 url =require('url');
var index = require('./routes/index');
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('/', index);
app.get('/*',function(req,res){
console.log('node js request call');
var pathname2 = url.parse(req.url);
console.log('pathname-1:'+pathname2);
console.log('pathname-2:'+__dirname);
console.log('pathname-3:'+__filename);
console.log(url.parse(index));
//console.log('basw path:'+process.env.PWD);
res.sendFile(path.resolve('public/index.html'));
});
// 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;
Use cheerio module for extracting the DOM at server side.
create utility.js
var cheerio = require('cheerio');
var fs = require('fs');
var utility = {
getBasePath : function (filePath) {
fs.readFile(filePath, function (err, html) {
if (err) { throw err; }
else {
$ = cheerio.load(html.toString());
return $('base').attr('href');
}
});
}
};
module.exports = utility;
update your 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 url =require('url');
var index = require('./routes/index');
var app = express();
var utility = require('./utility'); /// load your module
// 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('/', index);
app.get('/*',function(req,res){
console.log('node js request call');
var basePath = utility.getBasePath('./index'); /// call your funtion here ///
var pathname2 = url.parse(req.url);
console.log('pathname-1:'+pathname2);
console.log('pathname-2:'+__dirname);
console.log('pathname-3:'+__filename);
console.log(url.parse(index));
//console.log('basw path:'+process.env.PWD);
res.sendFile(path.resolve('public/index.html'));
});
// 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
my app's idea is simple. a user inputs text and then it gets diplayed and saved into the db. The problem am having is that it displays blank. I have a lot of code so am going to put the bare minimum.
my server :
// dependencies
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var hash = require('bcrypt-nodejs');
var path = require('path');
var passport = require('passport');
var localStrategy = require('passport-local' ).Strategy;
var meetupsController = require('./meetups-controller');
// mongoose
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/mean-auth');
// user schema/model
var User = require('./models/user.js');
// create instance of express
var app = express();
// require routes
var routes = require('./routes/api.js');
app.get('/api/meetups', meetupsController.list);
app.post('/api/meetups', meetupsController.create);
// define middleware
app.use(express.static(path.join(__dirname, '../client')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// configure passport
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// routes
app.use('/user/', routes);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '../client', 'index.html'));
});
// error hndlers
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res) {
res.status(err.status || 500);
res.end(JSON.stringify({
message: err.message,
error: {}
}));
});
app.use(bodyParser());
app.use('/js', express.static(__dirname + '/client/js'));
//REST API
module.exports = app;
my main angular controller
var myApp = angular.module('myApp', ['ngRoute','ngResource']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my html partial
<body>
<div id='main' ng-controller="loginController">
<form ng-Submit="post()">
<input required type="text" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="button" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class='post' ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.created_by}} says {{post.text}} at {{post.created_at}}</p>
</div>
<div ng-controller="logoutController">
<a ng-click='logout()' class="btn btn-default">Logout</a>
</div>
<div ng-controller="logoutController">
<a ng-click='gotoregister()' class="btn btn-default">register</a>
</div>
</div>
</div>
<div ng-controller="meetupsController">
<h1>There are {{meetups.length}} meetups</h1>
<ul>
<li ng-repeat="meetup in meetups">
{{meetup.name}}
</li>
</ul>
<form ng-submit="createMeetup()">
<input type="text" placeholder="Meetup name" ng-model="meetupName"></input>
<button type="submit">Add</button>
</form>
</div>
</body>
please help
I'm not sure what you mean by "displays blank", but there is likely an issue with these lines:
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.meetups = []
If $scope.meetups is assigned results, you may be overwriting that value with $scope.meetups = []. Remember that the $resource will resolve asynchronously, so assignments won't exactly happen in the order they are written. Try removing the $scope.meetups = [] line.
I can't figure out where I missed to add something. I get the following error: Cannot GET /portal/destroybox/5797318673cf3f581163455c when I click on delete or update icons in portal.ejs:
(createbox in portal.ejs works and creates the item and stores it in the db, and then I forEach in the table to show all items with update and delete icons behind each item. Also the // todo test part in server.js is for another part of my app and that works, nothing to do with the portal/box part. I also do not have route in server.js for createbox, but that part works, so why do I need it for destroybox if I need it at all?)
portal.ejs
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Vm</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<% boxes.forEach( function ( box ){ %>
<tr>
<td>
<%= box.box_name %>
</td>
<td>
<%= box.vm %>
</td>
<td>
<a class="fa fa-wrench" aria-hidden="true" href="/portal/editbox/<%= box._id %>" title="Update this box"></a>
</td>
<td>
<a class="fa fa-trash-o" aria-hidden="true" href="/portal/destroybox/<%= box._id %>" title="Destroy this box"></a>
</td>
</tr>
<% }); %>
</tbody>
</table>
<p>
<strong>Add new box to `available boxes`</strong>
<br>
</p>
<form action="/createbox" method="post">
<div class="form-group">
<label>Box name</label>
<input type="text" class="form-control" name="box_name">
</div>
<div class="form-group">
<label>VM</label>
<input type="text" class="form-control" name="vm">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" name="description">
</div>
<button type="submit" class="btn btn-warning btn-lg">Add box</button>
</form>
server.js
// server.js
// set up ======================================================================
// get all the tools we need
// mongoose setup
var db = require('./config/database.js');
require('./app/models/db');
require('./app/models/box');
var express = require('express');
var http = require('http');
var path = require('path');
var engine = require('ejs-locals');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var static = require('serve-static');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var routesindex = require('./routes/index');
//var routesbox = require('./routes/boxi');
// configuration ===============================================================
mongoose.connect(db.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.engine('ejs', engine);
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({
secret: 'secretkeykeykeykey'
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
var routes = require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
// todo test
app.use(routesindex.current_user);
app.get('/ind', routesindex.ind);
app.post('/ind/create', routesindex.create);
app.get('/ind/destroy/:id', routesindex.destroy);
app.get('/ind/edit/:id', routesindex.edit);
app.post('/ind/update/:id', routesindex.update);
app.use(static(path.join(__dirname, 'public')));
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
routes.js
// =====================================
// PORTAL ==============================
// =====================================
// show the signup form
app.get('/portal', isLoggedIn, function (req, res) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Box.
find({
user_id: user_id
}).
sort('-updated_at').
exec(function (err, boxes) {
if (err) return next(err);
res.render('portal', {
boxes: boxes
});
});
});
app.post('/createbox', isLoggedIn, function (req, res) {
new Box({
user_id: req.cookies.user_id,
box_name: req.body.box_name,
vm: req.body.vm,
description: req.body.description,
updated_at: Date.now()
}).save(function (err, box, count) {
if (err) return next(err);
res.redirect('/portal/');
});
});
app.get('/destroybox/:id', isLoggedIn, function (req, res) {
Box.findById(req.params.id, function (err, box) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
if (box.user_id !== user_id) {
return utils.forbidden(res);
}
box.remove(function (err, box) {
if (err) return next(err);
res.redirect('/portal/');
});
});
});
app.get('/editbox/:id', isLoggedIn, function (req, res) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
Box.
find({
user_id: user_id
}).
sort('-updated_at').
exec(function (err, boxes) {
if (err) return next(err);
res.render('editbox', {
title: 'Vagrant Box',
boxes: boxes,
current: req.params.id
});
});
});
app.post('/updatebox/:id', isLoggedIn, function (req, res) {
Box.findById(req.params.id, function (err, box) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;
if (box.user_id !== user_id) {
return utils.forbidden(res);
}
box.box_name = req.body.box_name;
box.vm = req.body.vm;
box.description = req.body.description;
box.updated_at = Date.now();
box.save(function (err, box, count) {
if (err) return next(err);
res.redirect('/portal/');
});
});
});
Because you don't have routes for that as the error states:
app.get('/destroybox/:id'
You can see you have a route from root / to destroybox then :id etc. While you are having a href of:
href="/portal/destroybox/<%= box._id %>"
from root / to portal and then destroybox then the id. Which is no where defined in the config.
Solution is to change the href to:
href="/destroybox/<%= box._id %>"
same goes for other href attributes too.
I'm using auth0 to act as my admin panel's login, and it's running great. A problem that I'm having is that in node, I cannot for some reason access 'req.user' as it returns unidentified. This is a pretty basic setup here. I have console logged req.headers and an authentication header is set.
Here is the node 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();
var Parse = require('node-parse-api').Parse;
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
// 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('/bower_components', express.static(__dirname + '/bower_components'));
app.Parse = new Parse(options.app_id, options.api_key);
app.use('/api', routes(app), expressJwt({secret: 'Mode'}));
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '/public') });
});
module.exports = app;
Here is the AngularJS code.
var app = angular.module('EnragedGamers', ['angularMoment', 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt'])
.config(function(authProvider, $routeProvider, $locationProvider, $httpProvider, jwtInterceptorProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'Home'
})
.when('/article/:article_id', {
templateUrl: 'article.html',
controller: 'Article'
})
.when('/admin-panel/login', {
templateUrl: 'admin-login.html',
controller: 'Admin-Login'
})
.when('/admin-panel', {
templateUrl: 'admin.html',
controller: 'Admin',
requiresLogin: true
});
authProvider.init({
domain: 'enragedgamers.auth0.com',
clientID: 'MpTkAl4eosjl3SB682ZGSSrJYi03QiZp',
loginUrl: '/admin-panel/login'
});
jwtInterceptorProvider.tokenGetter = ['store', function(store) {
// Return the saved token
return store.get('token');
}];
$httpProvider.interceptors.push('jwtInterceptor');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This hooks al auth events to check everything as soon as the app starts
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
// Either show the login page or use the refresh token to get a new idToken
$location.path('/');
}
}
});
});
Here is the routes file code
var express = require('express');
var router = express.Router();
module.exports = function(app){
router.get('/admin/hello', function(req, res){
console.log(req.user)
res.status(201).json({'human': 'Hello'})
console.log(req.body);
});
return router;
}
It seems that you're missing your secret on the node side and the middle man for actually authenticating.
See https://github.com/auth0/express-jwt
var jwt = require('express-jwt');
app.use(jwt({ secret: 'your secret key here'}));
Using nodeJs,ExpressJS(~4)
This is my structure:
controllers/searchController.js
public/javascripts/search.js (js client code that will run on browser)
public/search.html
server.js
app.js
searchController.js:
var express = require('express');
var router = express.Router();
var esService = require('../services/esService');
var Q = require('q');
var html_dir = './public/';
router.get("/home", function (req, res) {
res.sendfile(html_dir + 'search.html');
})
router.get("/search", function (req, res) {
...
})
module.exports = router;
app.js:
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 searchController = require('./controllers/searchController');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(__dirname, '/public'));
app.use('/', searchController);
/// 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;
search.html:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
........
<div id="tfheader">
<form id="tfnewsearch" method="get" onsubmit="return handleClick()">
<input id="myinput" type="text" class="tftextinput" name="q" size="21" maxlength="120">
<input type="submit" value="search" class="tfbutton">
</form>
<div class="tfclear"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="javascripts/prettyprint.js"></script>
<script src="javascripts/search.js"></script>
...
</body>
</html>
and this is search.js:
function handleClick() {
var inputParam = document.querySelector("#myinput").value;
$.get('search?termToSearch=' + inputParam, function (responseText) {
console.log(responseText);
$("#resultlist").empty().append(prettyPrint(responseText));
});
return false;
}
Now when I acesss to: http://localhost:3000/home I am getting the folloing error on the browser:
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/search.js
Request Method:GET
Status Code:404 Not Found
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/javascripts/prettyprint.js
Request Method:GET
Status Code:404 Not Found
Any idea why?
You should change
app.use(express.static(__dirname, '/public'));
to:
app.use(express.static(__dirname + '/public'));
But if you really want to fix this problem it's better to use an prefix for static file like this:
app.use('/public', express.static(__dirname + '/public'));
and then load your Javascript files in this way:
<script src="public/javascripts/prettyprint.js"></script>
<script src="public/javascripts/search.js"></script>