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.
Related
I'm working with an Angular-Gulp-Browsersync-Express app and I'm having trouble getting angular's $http resource to POST a simple "contact us" form to my express server.
Every time I try to submit my form I get the following error:
POST http://localhost:8080/submitContactUsForm 404 (Not Found)
Cannot POST /submitContactUsForm
To be up front, I've got much more experience working with the front-end than I do with the back-end so it could very well be that I've got the wrong server setup.
Here is my Express Server:
'use strict';
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var http = require('http');
var routes = require('.././src/index.module.js');
// var contactController = require('.././api/http/controllers/contactcontroller.js');
// require database data modeling via mongoose
var mongoose = require('mongoose');
// Express Session allows us to use Cookies to keep track of
// a user across multiple pages. We also need to be able to load
// those cookies using the cookie parser
var session = require('express-session');
var cookieParser = require('cookie-parser');
// Flash allows us to store quick one-time-use messages
// between views that are removed once they are used.
// Useful for error messages.
var flash = require('connect-flash');
// Use express and set it up
var app = express();
app.use(cors());
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/submitContactUsForm', function(req, res) {
console.log('it hit the server');
})
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync').create();
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init({
startPath: '/',
cors: true,
browser: browser,
port: 8080,
server: {
baseDir: baseDir,
routes: routes,
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
next();
}
},
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['setenvconstants','watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['setenvconstants','build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
Here is the Angular Controller I am trying to post from:
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.controller('ContactController', ContactController);
function ContactController($http, $log) {
// controllerAs syntax
var vm = this;
vm.contactInfo = {
email: vm.email
}
vm.processContactForm = function() {
return $http.post('/submitContactUsForm', vm.contactInfo)
.then(returnSendSuccessful)
.catch(sendFail);
function returnSendSuccessful(response) {
$log.log(response.data);
return response.data;
}
function sendFail(err) {
return $log.error(err.data);
}
}
}
})();
Here are my Client-Side Routes:
(function() {
'use strict';
angular
.module('commonSenseDietApp')
.config(routeConfig);
function routeConfig($routeProvider) {
// Home Page
$routeProvider
.when('/', {
templateUrl: 'app/views/pages/home.html',
controller: 'MainController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// About Page
$routeProvider
.when('/about', {
templateUrl: 'app/views/static/about.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Terms of Use Page
$routeProvider
.when('/terms-of-use', {
templateUrl: 'app/views/static/terms-of-use.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Privacy Policy Page
$routeProvider
.when('/privacy-policy', {
templateUrl: 'app/views/static/privacy-policy.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Contact Us Page
$routeProvider
.when('/contact', {
templateUrl: 'app/views/pages/contact.html',
controller: 'ContactController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Answer Page
$routeProvider
.when('/answer', {
templateUrl: 'app/views/pages/answer.html',
controller: 'AnswerController',
controllerAs: 'vm'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// How It Works Page
$routeProvider
.when('/how-it-works', {
templateUrl: 'app/views/static/how-it-works.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
// Algorithm Explainer Page
$routeProvider
.when('/meet-ONNA', {
templateUrl: 'app/views/static/meet-ONNA.html'
})
.otherwise({
controller: 'Error404Controller',
templateUrl: 'app/views/errors/404.html'
});
}
})();
Here is my contact form markup:
<section>
<div class="contact-us-title">
<h1>Contact Us</h1>
</div>
<form class="contact-us-form" name="contactUsForm" ng-submit="vm.processContactForm()">
<div class="form-group">
<input placeholder="name" type="text" name="name" ng-model="vm.name" class="form-control" required />
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.name.$error.required">Required!</span>
</div>
<div class="form-group">
<input placeholder="Email" type="email" name="email" ng-model="vm.email" class="form-control" required />
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.email.$error.required">Required!</span>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.$error.email">Invalid email!</span>
</div>
<div class="form-group">
<input name="headline" placeholder="Headline" type="text" ng-model="vm.headline" class="form-control" required/>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.headline.$error.required">Required!</span>
</div>
<div class="form-group">
<textarea name="message" placeholder="Message" type="textbox" ng-model="vm.message" class="form-control" required></textarea>
<span class="label label-danger" ng-show="vm.submitted && contact-us-form.subjectList.$error.required">Required!</span>
</div>
<input type="submit" id="submit-contact-form-btn">
</form>
</section>
I'm also not seeing anything logging to console in the terminal. Any insight on this would be super helpful and very appreciated.
Eureka I found the answer!
Turns out my lack of experience with express playing nice with browersync was certainly a hinderance for me here. The answer lied in Proxying browsersync to express and the use of gulp-nodemon package. After some restructuring I've got the right setup:
My Browser-Sync server and gulp init tasks:
'use strict';
var path = require('path');
var port = process.env.PORT || 8080;
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync').create();
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
var nodemon = require('gulp-nodemon');
var reload = browserSync.reload;
function browserSyncInit(baseDir, browser) {
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init({
startPath: '/',
cors: true,
browser: browser = browser === undefined ? 'default' : browser,
proxy: 'http://localhost:8081',
port: port
// https: true
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]' // Only needed for angular apps
}));
// Run Gulp tasks
gulp.task('serve', ['browser-sync','setenvconstants','watch']);
gulp.task('browser-sync', ['nodemon'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['setenvconstants','build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});
gulp.task('nodemon', [], function(done) {
var running = false;
return nodemon({
script: 'api/app.js',
watch: ['api/**/*.*', 'src/**/*.*']
})
.on('start',function() {
if (!running) {
done();
}
running = true;
})
.on('restart', function() {
setTimeout(function(){
reload();
}, 500);
});
});
My Express server:
var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');
var port = process.env.PORT || 8081;
var cors = require('cors');
var path = require('path');
var publicRoutes = require('./http/routes/web.js');
// require database data modeling via mongoose
var mongoose = require('mongoose');
// Express Session allows us to use Cookies to keep track of
// a user across multiple pages. We also need to be able to load
// those cookies using the cookie parser
var session = require('express-session');
var cookieParser = require('cookie-parser');
// Flash allows us to store quick one-time-use messages
// between views that are removed once they are used.
// Useful for error messages.
var flash = require('connect-flash');
// Use Express and set it up
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
// Parse requests to JSON
app.use(bodyParser.json({type: '*/*', limit: '50mb'}));
// set Jade as the view engine
app.set('view engine', 'jade');
// tell server where to find our views
app.set('views', __dirname + '/.././src/app/views');
// make sure bower components are installed.
app.use('/underscore', express.static(path.resolve('.././node_modules/underscore')));
// tell our server where to find static assets depending on the environment.
process.env.NODE_ENV == 'production' ? app.use(express.static(path.join(__dirname + '/../..'))) : app.use(express.static(path.join(__dirname + '/.././dist')));
// enable cors
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": ["Origin, X-Requested-With, Content-Type, Accept, Authorization"],
"preflightContinue": false
}));
// Pull in our public routes
app.use('/api', publicRoutes);
// Listen
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.", port, port);
}
});
I'm now able to $http.post from my Angular controller considering the route prefix in my express server:
vm.processContactForm = function() {
return $http.post('/api/submitContactUsForm', vm.contactInfo)
.then(returnSendSuccessful)
.catch(sendFail);
function returnSendSuccessful(response) {
$log.log(response);
// return response.data;
}
function sendFail(err) {
return $log.error(err.data);
}
}
The only issue I'm having now is with...
process.env.NODE_ENV == 'production' ? app.use(express.static(path.join(__dirname + '/.././src'))) : app.use(express.static(path.join(__dirname + '/.././dist')));
wherein '/dist' is served just fine but '/src' only serves a blank index.html page to my localhost. I'll post this as a new question and consider this issue solved. Thanks for the help!
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
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'}));
I am pretty new to AngularJS, and even newer to ExpressJS and Mongoose. I have been following a tutorial to post to, and get from my database, but I'm having trouble adding delete functionality.
Here is where I call my delete function:
<ul ng-repeat="disease in diseases">
<li>
{{ disease.name }}: {{ disease.chipped }},
{{ disease.received }},
{{ disease.smashed }},
{{ disease.complete }}
</li>
<button ng-click="removeDisease(disease)"></button>
</ul>
... and in my controller I have:
app.controller('MainCtrl', [
'$scope',
'TrelloApi',
'diseases',
function($scope, TrelloApi, diseases){
$scope.diseases = diseases.diseases;
$scope.removeDisease = function(disease) {
console.log(disease);
diseases.destroy(disease);
}
}
]);
...which calls my diseases factory:
app.factory('diseases', [
'$http',
function($http){
var o = {
diseases: []
};
o.destroy = function(disease) {
return $http.delete('/diseases/' + disease._id).success(function(data){
console.log("Disease " + disease.name + " has been removed!");
o.getAll();
});
};
return o;
}
]);
This returns with a 404 error:
DELETE http://localhost:4000/diseases/<id> 404 (Not Found) even though in my my routes include:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Disease = mongoose.model('Disease');
// Not functional
router.delete('/diseases/:id', function(req, res, next) {
console.log(req);
});
// Functional
router.post('/diseases', function(req, res, next) {
var disease = new Disease(req.body);
disease.save(function(err, diseases){
if(err){ return next(err); }
res.json(diseases);
});
});
... and ui.router includes:
app.config([
'TrelloApiProvider',
'$stateProvider',
'$urlRouterProvider',
function(TrelloApiProvider, $stateProvider, $urlRouterProvider) {
.state('diseases', {
url: '/diseases/{id}',
templateUrl: '/javascripts/home/_diseases.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
]);
There is also a template found at /javascripts/home/_diseases.html. I have a feeling I am missing one piece but I just can't figure out what it is.
Be sure you start Express HTTP server:
const express = require('express');
const router = express.Router();
router.delete('/diseases/:id', function(req, res, next) {
const id = req.params.id;
console.log(id);
});
const app = express();
app.use('/', router);
const server = http.createServer(app).listen(8080, serverCallback);
function serverCallback() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server listening on ${host}:${port}`);
}
My RESTful MEAN application has a node.js server for back end and HTTP-server in the front end. Following is the project structure:
When i run My Directory/app/HTTP-server from the console and do the browsing its displaying the page as follows with directory listing/browsing:
Once i click on views the pages are rendering. Following is my app.js:
'use strict';
var app = angular.module('app', ['ngRoute', 'authControllers', 'authServices']);
var authControllers = angular.module('authControllers', []);
var authServices = angular.module('authServices', []);
var options = {};
options.api = {};
//dev URL
options.api.base_url = "http://localhost:3000";
app.config(['$locationProvider', '$routeProvider',
function($location, $routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'authCtrl'
}).
when('/login', {
templateUrl: 'partials/signin.html',
controller: 'authCtrl'
}).
when('/register', {
templateUrl: 'partials/signup.html',
controller: 'authCtrl'
}).
when('/me', {
templateUrl: 'partials/me.html',
controller: 'authCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
}]);
app.run(function($rootScope, $location, $window, AuthenticationService) {
$rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
//redirect only if both isAuthenticated is false and no token is set
if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication
&& !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {
$location.path("/login");
}
});
});
server.js:
var express = require('express'),
jwt = require('express-jwt'),
bodyParser = require('body-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('express-error-handler'),
tokenManager = require('./server/config/token_manager'),
secret = require('./server/config/secret'),
http = require('http'),
path = require('path');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'app')));
var routes = require('./server/routes');
routes.users = require('./server/routes/users.js');
var env = process.env.NODE_ENV || 'development';
// development only
if (env === 'development') {
app.use(errorHandler());
}
// production only
if (env === 'production') {
// TODO
}
app.all('*', function(req, res, next) {
res.set('Access-Control-Allow-Origin', 'http://localhost');
res.set('Access-Control-Allow-Credentials', true);
res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
if ('OPTIONS' == req.method) return res.send(200);
next();
});
/*
Login
*/
app.post('/login', routes.users.login);
app.post('/user/register', routes.users.register);
app.get('/me', routes.users.me);
/*
Logout
*/
app.get('/logout', jwt({secret: secret.secretToken}), routes.users.logout);
process.on('uncaughtException', function(err) {
console.log(err);
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
What needs to be done to disable this directory listing/browsing or to simply render my view on http://localhost:8080/ ?
In your server.js change
express.static(path.join(__dirname, 'app'));
with
express.static(path.join(__dirname, 'app'), {index: false});