Angular Ui-Router isn't routing while using node.js - node.js

I am using angular ui router. The router seems to work perfect on the home page index.html. But any other navigation doesn't work.
Here is my stateprovider angular:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: "../partials/home/index.html"
})
.state("login", {
url:"/login",
templateUrl: "../partials/account/login.html"
})
.state("register", {
url: "/register",
templateUrl: "../partials/account/register.html"
})
.state("values", {
url: "/values",
templateUrl: "../partials/test/values.html"
})
;
});
HTML in my main index.html:
<!--Content -->
<div class="container">
<div ui-view></div>
</div>
<!-- END Content -->
When I navigate the the page localhost:8080/login I get this:
I would think I shouldn't even be seeing this page if it can't find it. Shouldn't it redirect me back to "/" because of $urlRouterProvider.otherwise(). Besides that point though the template url /partials/account/login.html Does Exist.
I am somewhat new to node.js and I am curious if the note file server is trying to route and trumping my angular one? I am using http-server which is probably the most common one.
I am also using Express Node if that helps. And here is the code for app.js where I think the problem may be coming from:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = 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');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
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 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;

I figured it out. Doing the below made it work.
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
The entire app.js incase anyone is curious where it goes.
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendfile(__dirname + '/public/index.html');
});
app.use('/', routes);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Of course this will need to be in your angular code:
app.config(["$locationProvider", function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
One thing to note that got me. You must restart the server for this to work. ctr+c then paste this code then restart server. Good luck

have you tried using the same directory for your partials :
moving partials/account/login.html" to partials/home/login.html"
Also, are you using your own server.js express configuration, or a yeoman fullstack ?
angular is clearly handling the routing, but it seems that nodejs is not finding the assets...
Be sure to have a specific task for serving partial files in your server.js
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
function serve_index(req,res){
res.render('index');
}
// Angular Routes
app.get('/partials/*', serve_partial);
app.get('/*', serve_index);
for your case, it might me something as :
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = 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');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
function serve_partial(req,res){
var stripped = req.url.split('.')[0];
var requestedView = path.join('./', stripped);
res.render(requestedView, function(err, html) {
if(err) {
res.render('404');
} else {
res.send(html);
}
});
}
app.use('/partials/*', serve_partial);
app.use('/', routes);
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 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;

As i see you request to your node api which there isnt any route like /login and you get 404.
You should try localhost:8080/#/login

Related

Express + node - routing 101

I am brand new to node and express and I hope that the SO community can help with this very introductory question.
I am simply trying to add an 'about' page with an /about route.
I added app.use('/about', about); in app.js, then created an 'about.js' in the directory 'routes', I added the following to my about.js file (below), and I created an about.jade file.
router.get('/about', function(req, res, next) {
res.render('about');
});
However, when I go to http://localhost:3001/about I get:
Not Found
404
Error: Not Found
my about.jade file is in the views directory along with layout.jade and index.jade.
My files below
/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 routes = require('./routes/index');
var users = require('./routes/users');
var about = require('./routes/about');
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.png')));
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('/', routes);
app.use('/users', users);
app.use('/about', about);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
routs/about.js:
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res, next) {
res.render('about');
});
module.exports = router;
Any help is appreciated, thanks.
Since you mounted the about router on /about via app.use('/about', about);, you would need to change
router.get('/about', function(req, res, next) {
res.render('about');
});
to something like
router.get('/', function(req, res, next) {
res.render('about');
});
in routes/about.js.

how to serve static files with nodejs in multiple routing

I am trying to make a website of my small bussiness of cables and wires
using nodejs express (ejs)
files are like:
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');
/* routes variables*/
var routes = require('./routes/index');
var cableWires = require('./routes/cableWires');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use(express.static('public/stylesheets'));
app.use(express.static('public/images'));
app.use(express.static('public/javascripts'));
/* routes */
app.use('/', routes); // index page
app.use('/cableWires', cableWires); //cables and wires
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
In routes/cablesWires.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('products_cableWires', { title: 'Umesh Electricals' });
});
router.get('/submersible_cables', function(req, res, next) {
res.render('submersible-cables', { title: 'Umesh Electricals' });
});
router.get('/house_wires', function(req, res, next) {
res.render('house-wires', { title: 'Umesh Electricals' });
});
module.exports = router;
When I go to cableWires page, everything is fine,
but when I go to house_wires page or submersible_cables page, it loads the content of ejs file but fails to load static files (css, javascript and images)
What could be the possible mistake am I doing
Its seems that when you make request to any route then it try to fetch that file from that URL path i.e - when you call /route1 then it will call the static file from relative path..so you have to change it to absolute path..
so change the static path and include "/" before static path
app.use(express.static('public')); app.use(express.static('/public/stylesheets')); app.use(express.static('/public/images')); app.use(express.static('/public/javascript
Let us know if its help

node express express.static prevents access from root path '/'

I am using express and I have a catch all route
router.use('*',function(){...});
and a root route
router.use('/', function(){...});
I have this route placed after the
app.use(express.static(path.join(__dirname, 'public')));
this causes my routes to not fire when placed below the previous line. however if I put my routes above it my catch all is also called on static asset requests. is there a way I can catch all requests except for the assets in my public folder including the route '/'? I don't want to resort to using regex and having to update it every time a directory is added to the public directory.
sorry for not being more details here are the relavant files
//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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
/* This is going to initialize the menubar for nwjs it is currently commented out as this is a non issue at this point
setTimeout(function () {
//initialize passport
var passport = require('./helpers/passport.js');
//setup routes
//setup window menu
console = window.console;
console.log(passport);
passport.init(app);
var gui = window.require('nw.gui');
var win = gui.Window.get();
var menu = new gui.Menu({
type: 'menubar'
});
menu.createMacBuiltin('jist', {
hideEdit: true,
hideWindow: true
});
gui.Window.get().menu = menu;
},1000);*/
// 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('/', routes);
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 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;
//window.location.href="http://localhost:3000";
this is my index router
//routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.use('*', function(req, res, nex){
var path = req.originalPath;
if(~['/users/login', '/users/signup'].indexOf(path) || req.user) return next();
if(!req.user) return res.redirect('/users/login');
});
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

http://localhost:3000/api/posts i am getting COULD NOT GET ANY RESPONSE. using POSTMAN

// this is app.js which is the main application 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 api = require('./routes/api');``
//var users = require('./routes/users');
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(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', routes);
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);
});
// 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;
and this is api.js which implements the RESTful API.Post is a resource and because of this we will implement a /posts API which will First we'll implement placeholder route handlers for the /posts api within api.js.
var express = require('express');
var router = express.Router();
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.json({message:"TODO create a new post in the database"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.json({message:"TODO get all the posts in the database"});
})
module.exports = router;
i am getting this on postman
You should be going to
http://localhost:3000/api/posts
Not
http://localhost:3000/routes/api/posts
..
Edit:
I didn't realize you're trying to call
req.send
Well that is not a method of
req (request)
You're looking for
res (response)
And on top of that you're trying to send a json result, not plain text so use
res.json
Instead of
res.send
I don't see you starting the server with app.listen(3000). You merely export the express app.
Or is there a different module that spins up the server?

Cannot get in Express - NodeJS

I create an express project, but i install the module with command npm install, but when i run node app.js , i cant get foo, can anyone help me ?
the error:
Error: Failed to lookup view "error" in views directory "C:\Users\Jack\Desktop\demo\views"
at EventEmitter.app.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\application.js:555:17)
at ServerResponse.res.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\response.js:938:7)
at C:\Users\Jack\Desktop\demo\app.js:55:7
at Layer.handle_error (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\layer.js:58:5)
at trim_prefix (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:300:13)
at C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:270:7
at Function.proto.process_params (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:321:12)
at IncomingMessage.next (C:\Users\Jack\Desktop\demo\node_modules\express\lib\router\index.js:261:10)
at fn (C:\Users\Jack\Desktop\demo\node_modules\express\lib\response.js:933:25)
at EventEmitter.app.render (C:\Users\Jack\Desktop\demo\node_modules\express\lib\application.js:557:14)
and the 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 routes = 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', 'ejs');
// 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')));
app.use('/', routes);
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 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: {}
});
});
app.get('/foo', function (req, res) {
res.send('Hello World!');
});
module.exports = app;
var port=3000;
var host='localhost';
app.listen(port, host);
console.log('Check url --> ' + host + ':' + port);
whaat's the problem here ? I install all module needed to run app.js but it's not work,plz help me, how can i fix this problem ?
There is a missing error view, the problem is not express, but the example you are running.
Create a file named error.ejs in your folder views.
error.ejs
<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>
But to get your application running with everything done, every files created and the folder architecture, you should use :
Express generator
MEAN.JS Full-Stack via the MEAN.JS Yo Generator
For the 404 NOT FOUND :
Add thoses files in your views folder. It will allow you to have every errors.
And for your /foo route, I just saw the route is UNDER the 404 not found middleware! Which means it will NEVER go to the route. You should write all your routes in the files of the routes/ folder
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();
// 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(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/foo', function (req, res) {
res.send('Hello World!');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var port=3000;
var host='localhost';
app.listen(port, host);
console.log('Check url --> ' + host + ':' + port);

Resources