Angular-BrowerSync-Express Cannot POST from client-side Express back-end route - javascript

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!

Related

Cannot post data from Angular.js to Node.js

I am creating a MEAN stack application using AngularJS and Node.js.
Here is my AngularJS code:
app.js:
var app = angular.module('crudApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider
.when('/employees/create', {
templateUrl : 'create.html',
controller : 'EmployeeController'
}).when('/nothing', {
templateUrl : 'main.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
}]);
app.controller('EmployeeController',function($scope,$http) {
$scope.save = function(data) {
$scope.data = JSON.stringify(data);
console.log(data);
$http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
console.log("posted successfully");
});
};
});
Here is my Node.js code:
server.js:
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(__dirname + '/angularjs/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('*',function(req, res) {
res.sendFile(__dirname + '/angularjs/public/index.html');
});
require('./node/routes')(app);
app.listen(8080);
routes.js:
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.body);
});
Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message.
But in node, I am unable to get the posted data in req.body.
I am getting the "create.html" content when I checked in browser "network".
Need someone's help.
Use this
module.exports = function(app) {
app.post('/employees/create-employee',function(req,res) {
console.log(req.body);
});
And for get you should use req.params
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.params);
});

App error displaying blank

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.

AngularJS lost data from multipartForm directive to routes

I am trying to build an Excel file uploader and parse the data in the routes to store it but it appears the data is lost in translation from the FormData sent in through the $http service route. I have no clue what to do! If you have any experience with this please help!
Html View:
<form ng-controller="myCtrl">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" ng-model="myFile.name">
</div>
<div class="form-group" >
<input type="file" file-model="myFile.file"/>
</div>
<button ng-click="Submit()">upload me</button>
</form>
Controller View:
myApp.controller('myCtrl', ['$scope', 'multipartForm', function($scope, multipartForm){
$scope.myFile = {};
$scope.Submit = function(){
var uploadUrl = '/upload';
multipartForm.post(uploadUrl, $scope.myFile);
}
}]);
Service View:
myApp.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data){
var fd = new FormData();
for(var key in data) {
fd.append(key, data[key]);
}
$http.post(uploadUrl, fd, {
transformRequest: angular.indentity,
headers: { 'Content-Type': undefined }
});
}
}])
Directive View:
myApp.directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, element, attrs){
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
})
})
}
}
}])
This is the route view where the data does not travel through.
module.exports = function (app) {
app
.post('/upload', function(req, res){
console.log(req.body);
console.log(req.files);
});
}
Server.js
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({ dest: './uploads/'});
var app = express();
// if using body-parser
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
// if mongoose, require mongoose
//require('./server/config/mongoose.js');
//routes
require('./server/config/routes.js')(app);
app.listen(8000, function () {
console.log('listening on port 8000');
})
the simple way is to use ng-file-upload. it's the most popular AngularJS directive for file upload using HTML5 with FileAPI polyfill for unsupported browsers.
Docs
Demo

Can't access req.user in Node.js server with Auth0/Angular

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'}));

AngularJS - How to disable directory browsing/listing when rendering views with Http web server

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});

Categories

Resources