So I am using Node.JS with Express as my backend and my servlet for API. I'm using AngularJS as my front end.
Through many Google searches, I finally solved my problem of using ngRoute with AngularJS and Node.js. And ended up with this:
var index = require('./routes/index');
var auth = require('./routes/auth');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.use('/api/auth', auth);
app.use('/', index);
app.use('*', index);
This is of course an excerpt of my app.js file at the root of my project.
Now when I make a call to my /api/auth/ I get told that node.js can't find my view. If I remove the app.use('*', index) the API works again but 'ngRoute' doesn't work.
How can I get to a point where both are working together? I also want to keep the address bar url as clean as possible.
My project was started with a call to yo node using yeoman if that helps any in the file/folder structure of my application.
Update
I'm not getting any answers or comments so maybe providing my full app.js file will be helpful and help me figure this out. Here it is.
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 index = require('./routes/index');
var auth = require('./routes/auth');
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('/api/auth', auth);
app.use('/', index);
app.use('*', index);
// 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;
Update 2
I have come to notice that the statement "ngRoute doesn't work" is vague. If I remove app.use('*', index) I receive this error if I try to go to an address other than the base address. I also receive this error when trying to access theapi/auth
Error: Failed to lookup view "error" in views directory "/Users/mitch/websites/splatform/views"
Update 3
The index.js file that my routes in app.js refer to includes this as well.
app.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
But, API calls shouldn't be going to the index.js File. Should be going to Auth.js.
Update 4
As requested, here is my $routeProvider from AngularJS.
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('frontStyles');
}]
}
})
.when('/app/login', {
templateUrl: 'templates/login.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.when('/app/dashboard', {
templateUrl: 'templates/dashboard.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
Also here is a simple run down of my file structure
app.js
routes
--auth.js
--index.js
views
--index.html ( angularJS Base )
public
--directives
--fonts
--images
--javascripts
--stylesheets
--templates ( Views that angularjs uses in `ng-view`
Call api's routes first then angularjs index.
For example: routesWeb.js
'use strict';
var express = require('express');
var path = require('path');
module.exports = function(app) {
var path_web = path.resolve(__dirname, '..');
var path_origin = path.resolve(__dirname, '../../');
app.use('/scripts',express.static(path_web + '/scripts'));
app.use('/pages',express.static(path_web + '/pages'));
app.use('/node_modules',express.static(path_origin + '/node_modules'));
app.route('/*')
.get(function(req, res){
res.sendFile(path_web + '/pages/ng-index.html');
});
}
pessoaRota.js
'use strict';
module.exports = function(app) {
var pessoasCtrl = require('../controllers/pessoasController');
app.route('/api/pessoas')
.get(pessoasCtrl.obter_todos_pessoas);
app.route('/api/pessoas/:pessoaId')
.get(pessoasCtrl.obter_pessoa_por_id);
app.route('/api/pessoasFeias')
.get(pessoasCtrl.obter_pessoas_feias);
};
server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.use(bodyParser.json());
app.use(cookieParser());
var server = app.listen(port, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Aplicação está on nesse endereço http://%s:%s", host, port)
});
require('./api/routes/pessoaRota.js')(app);
require('./web/routes/routesWeb.js')(app);
For more go here.
Related
I'm new to nodejs and I'm trying to use ejs to template my website. But when I tried to set the view engine, I keep getting the error code 500 - Internal Server Error. Here is my 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 engines = require('consolidate');
var index = require('./routes/index');
var main = require('./routes/main');
var suoimo = require('./routes/suoimo');
var vungtau = require('./routes/vungtau');
var video = require('./routes/video');
var dalat = require('./routes/dalat');
var app = express();
app.use(express.static('./'));
app.use(express.static('./public'));
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.engine('html', engines.mustache);
app.set('view engine', 'ejs');
// 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.use('/video', video);
app.use('/', index);
app.use('/suoimo', suoimo);
app.use('/vungtau', vungtau);
app.use('/main', main);
app.use('/dalat', dalat);
// 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;
But if I set the view and view engine like this:
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');
Everything work fine, anyone know why? Please help
I tested your code and everything works fine. But if I uninstall ejs I get error 500 Internal server error. I think that this is your problem. Try to run npm install ejs and try again with the same configuration, it should work fine now.
I am using socket.io to make a MEAN app. I am sending a event through my node, the event is defined in my index.js file which is included in my app.js. I am getting a 404 error while running my angular app.
let express = require('express');
let router = express.Router();
let server = require('http').Server(express);
let io = require('socket.io')(server);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', (socket) => {
console.log('User connected');
socket.emit('hello',{
greeting: 'Hello agam'
});
});
module.exports = router;
My angular code where i have included socket.io and calling my node server
import { Component, OnInit } from '#angular/core';
import * as socketIo from 'socket.io-client';
#Component({
selector: 'app-home-component',
templateUrl: './home-component.component.html',
styleUrls: ['./home-component.component.css']
})
export class HomeComponentComponent implements OnInit {
constructor() {
}
ngOnInit() {
const socket = socketIo('http://localhost:3000');
socket.on('hello', (data) => {
console.log(data);
});
}
}
The error which I am getting while running the app:
zone.js:2935 GET http://localhost:3000/socket.io/?
EIO=3&transport=polling&t=M4aQ8Fg 404 (Not Found)
This is My app.js :
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors({origin: true, credentials: true}));
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.use('/users', users);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Add:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
...
// And at end of file
http.listen(3000, () => {
console.log('started on port 3000');
});
I am new with Angular and Node/Express. Now I've setup a node/express server where I want to use angularjs on. I came as far as loading the main index.jade. I have some hrefs on this page that I want to use angular for to route between these links, but I can't seem to get it working. The console keeps telling me that the page that I'm linking to does not exist.
This is the app.js which is the server in express
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 index = require('./routes/index');
var users = require('./routes/users');
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.use('/users', users);
// 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;
This is the index.js on express
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
This is the jade file with my layout
doctype html
html(ng-app='myApp')
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js')
script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-route.js')
script(src='/javascripts/app.js')
base(href="/")
body
block content
div(ng-view)
This is the angular routing
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/red', {
templateUrl: '/views/red.jade'
}).when('/green', {
templateUrl: '/views/green.jade'
}).when('/blue', {
templateUrl: '/views/blue.jade'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
This is the error I get in the console
GET http://localhost:3000/views/blue.jade 404 (Not Found)
(anonymous) # angular.js:12578
q # angular.js:12323
(anonymous) # angular.js:12075
(anonymous) # angular.js:16843
$digest # angular.js:17982
$apply # angular.js:18280
(anonymous) # angular.js:14250
hg # angular.js:3734
d # angular.js:3722
angular.js:14516 Error: [$compile:tpload] http://errors.angularjs.org/1.6.3/$compile/tpload?p0=%2Fviews%2Fblue.jade&p1=404&p2=Not%20Found
at angular.js:38
at angular.js:19933
at angular.js:16843
at m.$digest (angular.js:17982)
at m.$apply (angular.js:18280)
at l (angular.js:12378)
at XMLHttpRequest.v.onload (angular.js:12532)
(anonymous) # angular.js:14516
(anonymous) # angular.js:11004
(anonymous) # angular.js:19937
(anonymous) # angular.js:16843
$digest # angular.js:17982
$apply # angular.js:18280
l # angular.js:12378
v.onload # angular.js:12532
You should render Jade templates on the server side, Angular don't know anything about Jade and how to work with it.
Setup Angular routing so that it does not contain "jade" extension
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/red', {
templateUrl: '/views/red'
}).when('/green', {
templateUrl: '/views/green'
}).when('/blue', {
templateUrl: '/views/blue'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
And modify index.js in that way
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/views/red', function(req, res, next) {
res.render('red', { title: 'Express red' });
});
router.get('/views/green', function(req, res, next) {
res.render('green', { title: 'Express green' });
});
router.get('/views/blue', function(req, res, next) {
res.render('blue', { title: 'Express blue' });
});
module.exports = router;
So now when Angular requests template by path "/views/blue" it sends request to Express server and in accordance with routes defined in index.js proper template will be rendered.
I am just going through nodejs, expressjs and coffeescript. My code is,
app.js
require('coffee-script').register();
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 index = require('./routes/index');
//var users = require('./routes/users');
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.use('/users', users);
require('./apps/authentication/routes')(app);
// 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;
My CoffeeScript Code is.
routes.coffee
routes = (app) ->
app.get "/login", (req , res) ->
res.render "views/login",
title: 'Login'
stylesheet: 'login'
module.export = routes
When i run project, i face following issue.
app.get("/login", function(req, res) {
^
ReferenceError: app is not defined
can anyone tell me why app variable is not defined at whereas i am passing app variable when requiring route?
If i remove white spaces from coffeescript file as mentioned below
routes = (app) ->
app.get "/login", (req , res) ->
res.render "views/login",
title: 'Login'
stylesheet: 'login'
module.export = routes
it return exception require(...) is not a function as mentioned below
require('./apps/authentication/routes')(app);
^
TypeError: require(...) is not a function
Thanks
Finally, I am able to fix this, it was syntax error in coffeescript.
I just changed
module.export
to
module.exports
Thanks,
I'm quite new to Node, I've been following a tutorial to build a simple server that serves dynamic pags with some basic routes but keep getting the Error: Cannot GET/ after running node server.js and calling localhost:3300 on the browser. My routes are defined externally and initialized using a routes.initialise() as follows:
//routes.js
var home = require('../controllers/home'),
image = require('../controllers/image'),
express = require('express');
module.exports.initialize = function(app, router) {
//var router = express.Router();
router.get('/', home.index);
router.get('/images/:image_id', image.index);
router.post('/images', image.create);
router.post('/images/:image_id/like', image.like);
router.post('/images/:image_id/comment', image.comment);
app.use('/', router);
};
I've searched far and wide but no solution forthcoming. I'm really frustrated and will need some help here.
I have a server.js that creates the server:
//server.js
var express = require('express'),
config = require('./server/configure'),
app = express();
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app = config(app);
var server = app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});
and a configure.js that configures the server:
//configure.js
var path = require('path'),
routes = require('./routes'),
exphbs = require('express3-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.engine('handlebars', exphbs.create({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts',
partialsDir: [app.get('views') + '/partials']
}).engine);
app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes.initialize(app, new express.Router());
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
also two files, home.js and image.js which are supposed to provide the default routes from configure.js:
//home.js
module.exports = {
index: function(req, res) {
res.send('The home:index controller');
}
};
//image.js
module.exports = {
index: function(req, res) {
res.send('The image:index controller ' + req.params.image_id);
},
create: function(req, res) {
res.send('The image:create POST controller');
},
like: function(req, res) {
res.send('The image:like POST controller');
},
comment: function(req, res) {
res.send('The image:comment POST controller');
}
};
Anytime I try to GET any of the links on the browser it returns the Cannot GET/ error. Any help will be greatly appreciated.
Thank you so much :)
I actually copied your exact code and it worked as you expect, though frankly it's got a bunch of indirection and at least one deprecated module. Maybe you have a PORT environmental variable set, and so the app isn't actually running on 3300?