Angular with Node - javascript

So Im trying to work AngularJS and Node. I am trying to set up client side routing but Im having some problems.
EDIT
So I changed up some code following https://github.com/scotch-io/starter-node-angular that #PareshGami suggested. I get the URLS to be hit but now the actual content doesnt load.
Here is my updated Code:
server.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
app.use(bodyParser.json());
require('./server/routes')(app);
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
my angular app.js:
(function (angular) {
'use strict';
var app = angular.module('eos', [
'ngRoute',
'ngResource',
'eos.opsCtrl',
'eos.dashboardCtrl'
]);
app.config(function ($routeProvider, $locationProvider){
$routeProvider.when(
'/',
{
templateUrl: 'views/dashboard.html',
pageName: 'Dashboard',
controller: 'dashboardCtrl'
}
);
$routeProvider.when(
'/ops',
{
templateUrl: 'views/ops.html',
pageName: 'Operations',
controller: 'opsCtrl'
}
);
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
}(window.angular));
My routes.js (new):
var opsController = require('./controllers/opsController');
module.exports = function(app) {
//path.join(__dirname, 'client');
// server routes ===========================================================
// handle things like api calls
// authentication routes
app.get('/api/ops', opsController.list);
app.post('/api/ops', opsController.create);
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendFile('index.html', { root: './client' });
});
};
Then rest is identical. And suggestions on why it is not loading the content in the ng-view?
FINALLY GOT IT TO WORK! My server.js was set up wrong.
Here is the correct server.js. Notice position of:
require('./server/routes')(app);
it needed to be father down for what I assume is the compile sequence
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
methodOverride = require('method-override');
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
require('./server/routes')(app);
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;

I was directed by PareshGami to look over this site 'setting-up-a-mean-stack-single-page-application'. After following that I was able to get the routing to work. The key to my problem was the ordering of my server.js file and the require('./server/routes')(app); part.

Related

What's wrong with my express.router().get method?

I'm trying to follow this tutorial, in which the author provides a sample code:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
And I tweaked it a little bit and here is my code:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({ message: 'Hello World!' });
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
The server runs perfectly but when I visit localhost:8081, I get the following message on my browser: Cannot GET /
What am I doing wrong here?
Since you added app.use('/api', router);
And your route is router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });
Then to access '/' you need to request with /api/
Update: If you have set the port on in env use that port or else you should be able to access using localhost:8081/api/
Hope it helps !
The above comment is correct.
You have added prefix '/api' to your local server and all incoming request will be http://localhost:<port>/api/<path>
app.use('/api', router);
If you want to access like this (without prefix) http://localhost:<port>/<path>
Please update your code to
app.use(router);

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

Angular ng-view not working with express

I'm trying work open page home of directory partials/home using ng-view and ng-view not working with express. A new page opens with render when acess http://localhost:3000/home. All routes defined for angular has no effect. I would like to know how to render my page partials/home.html in index.html using ng-view with express.
app.js
//módulos
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
load('routes').then('controllers').into(app);
server.listen(3000);
console.log('Site no ar ...');
module.exports = app;
Routes Express - index.js
module.exports = function (app) {
app.get('/', function(req, res){
res.render('index');
});
app.get('/:name', function(req, res){
var name = req.params.name;
res.render('partials/' + name);
});
app.get('*', function(req, res){
res.render('index');
});
};
Routes Angular - Location: public/app/app.js
var app = angular.module('appSiteFio',['ngRoute']);
app.config(function($routeProvider, $locationProvider){
// remove o # da url
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'mainController',
})
.when('/home', {
templateUrl : 'partials/home.html',
controller : 'homeController',
})
.otherwise ({ redirectTo: '/' });
});
I would suggest changing the index.js file to something like:
module.exports = function (app) {
app.use(express.static('/partials')); //here you can write your partials directory.
app.get('*', function(req, res){
res.render('index');
});
};
(Also change your templateUrl inside angular file with the partials prefix.);
that way angular will allways will be loaded and angular router will deal with all the views fetching from the static partials folder

AngularJS + NodeJS Routing - Not working

I am trying to make a basic application using the MEAN Stack.
I have been struggling for the past hour or so to make a basic route work, but I fail miserably.
Whenever I access my application on / the template provided to the Angular route will not render the template, even if I can manually access it at templateUrl in the browser.
This is my code:
express.js
var express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
logger = require('morgan'),
cookieParser = require('cookie-parser');
module.exports = function(app, config){
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({secret: 'contact demo'}));
app.use(express.static(config.rootPath + '/public'));
};
routes.js
var mongoose = require('mongoose'),
Contact = mongoose.model('Contact');
module.exports = function(app, router) {
router.get('/partials/*', function(req, res) {
res.render('../../public/app/' + req.params[0]);
});
router.get('*', function(req, res) {
res.render('index');
});
app.use('/', router);
};
server.js
// Module Dependencies
var express = require('express'),
mongoose = require('mongoose');
// Initialize Express Application
var app = express(),
env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// Config Parameters
var config = require('./server/config/config')[env];
// Invoke Express Config File
require('./server/config/express')(app, config);
// Invoke Mongoose Config File
require('./server/config/mongoose')(config);
// Invoke Routes File
require('./server/config/routes')(app, express.Router());
app.listen(config.port);
console.log('Listening on port ' + config.port + '...');
app.js
angular.module('demo', ['ngResource', 'ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {templateUrl: '/partials/main/main'});
$locationProvider.html5Mode(true);
});
layout.jade
doctype
html
head
title Contact Management Application
link(rel="stylesheet" href="/vendor/bootstrap/dist/css/bootstrap.min.css")
link(rel="stylesheet" href="/css/style.css")
body(ng-app="demo")
block main-content
include scripts
index.jade
extends ../includes/layout
block main-content
h1 Hello World
section.content
div(ng-view)
main.jade
section.content
h1 I should be rendered!
EDIT
This is my folder structure:
--public/
--app/
--main/
--main.jade
--app.js
--css/
--vendor/
--server/
--config/
--express.js
--routes.js
--includes/
--layout.jade
--scripts.jade
--views/
--index.jade
--server.js
Where are you calling the REST commands in your angular code? It seems like you're just navigating to a different page within the app but you aren't telling it to pull from the server.

Get route error in Node.js/Express

I get an error Cannot Get /. this is my folder structure
This is the route.js file:
//route.js
'use strict';
var app = require('../../config/express');
var router = app.Router();
/* Get Home Controller */
var homeController = require('../controllers/index');
router.get('/index', homeController.index); //it isn't recognized
app.use('/', router);
'use strict';
/*
* GET /
* Home Page
*/
exports.index = function(req, res){
res.render('index', {
'pageTitle': 'Express page'
});
};
'use strict';
/* Import Express module */
var express = require('express');
var path = require('path');
//var bodyParser = require('body-parser');
/* Import env config parameters */
var settings = require('./env/settings');
/* Create express server */
var app = express();
/* Settings Application */
app.set('port', settings.port);
app.set('views', path.join(__dirname, '/frontend/views'));
app.set('view engine', 'jade');
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/assets'));
module.exports = app;
I know that it is a problem on routing but I have tried to fix it
Cannot Get / is exactly what is says. You have not defined any routes that match that path. You have defined /index, but not /, and they are two different URLs. index.html-style behavior is not provided by Express in routes. It is available with the static-file middleware if you want it though.
So change it to:
router.get('/', homeController.index);
or if you also want /index to work, just do both:
router.get('/', homeController.index);
router.get('/index', homeController.index);

Categories

Resources