can not find 404 error with node js request - angularjs

I am following the directory structure given here:
angular-fullstack
I have a folder name Musician in server/api.
In this folder,
Musician
|
|----->index.js
|----->Musician.controller.js
|----->Musician.model.js
In index.js,
I give the routes as:
use strict';
var express = require('express');
var musicians = require('./Musician.controller');
var auth = require('../../auth/auth.service');
var router = express.Router();
router.get('/musicians', musicians.findAll);
router.get('/musicians/:id', musicians.findById);
router.post('/musicians', auth.isAuthenticated(), musicians.add);
router.put('/musicians/:id', musicians.update);
router.delete('/musicians/:id', musicians.delete);
router.get('/import', musicians.import);
module.exports = router;
It gives the error that way. But if I put this in my routes.js, It works.
How do I get these routes working right from index.js?
As per the directory structure and articles on web, it should be working from index.js.
Error:

Related

How to access Node JS route Url in Angular JS site

I am working on a site which is in Angular JS language. Now for website, I have to generate dynamic sitemaps and for this I used Node JS and created a xml.js route in node and wrote hello world.
Now the problem is, I am not able to use access this xml.js in angular site. Here is xml.js code :
var express = require("express");
var router = express.Router();
router.get("/test", function() {
console.log("hello world");
});
module.exports = router;
Here is server.js code :
var express=require('express');
var xml = require("./xml");
var app=express();
app.use('/xml',xml);
app.use('/',express.static('app'));
app.listen(9000) ;
Now whenever I try to access http://192.168.0.19:9000/xml/test I am being redirected to home page always.
Can someone help me out ?
You can try this code.This code work for me
You need to pass req and res parameter.
router.get('/', function (req, res) {
res.send('home page')
})
router.get("/test", function (req, res) {
console.log("hello world");
res.send('test page')
})

Add package routes into main app routes with Express

im writing my own MEAN stack. I want to structure it in a horizontal architecture similar to how mean.io does theirs. Each package has its own server and public folder with its own routes.
I have a server.js which is my main express file at the root level. When I start things with npm start I would like to have each package register its own routes / mount its own routes on my main app instance. For some reason though im getting express errors when I try to do this.
Can anyone advise me? Thanks so much. https://github.com/peb7268/LMFM.git
In the submodule / package ( in this case users ) I needed to mount things differently:
var express = require('express');
var router = express.Router();
var Users = function(){
var self = this;
self._name = 'users';
console.log('initializing ' + self._name);
router.route('/')
.get(function(req, res){
res.send('finding '+ self._name);
});
}
module.exports = {'router': router, 'instance': new Users()};
Instead of router.route('/users');
Because when you do app.use('/users', router); the '/', default path will collide with '/users' in the sub module.

javascript error TypeError: Cannot read property 'post' of undefined

I have created a MEAN stack web application by following the tutorial http://start.jcolemorrison.com/building-an-angular-and-express-app-part-2/
After adding the signup.js as below,
var express = require('express');
var router = express.Router();
router.post('/', function (req, res) {
I am getting below error :
router.post('/', function (req, res) {
^
TypeError: Cannot read property 'post' of undefined
Please guide me.
Not sure what that tutorial is trying to get you to do, but try and see if this works:
var express = require('express');
var app = express();
app.post('/', function (req, res) {
res.json({hello: "world"});
});
If it doesn't, then you've probably got a syntax error somewhere that's preventing router from initializing.
If it does work, then my only thought is that since Router() is new to Express 4.X, perhaps you're not using a 4.X version of Express? You can check by doing:
npm list express
And if necessary, upgrade by doing:
npm install express

GET error MEAN App

I've been learning how to use the MEAN stack in order to build web apps and so far it's been a lot of fun. Instead of using yeoman generators or npm app to generate my code for me, I've been building my whole app from the ground up. This way I know how each piece connects and what is going on with my app. I was just starting to connect the front and back end of my app when I looked at the developer console and saw
GET http://blog.dev/bower_components/angular/angular.js
Not only angular, but every other resource I have (Modernizr, angular-routes, mootools, restangular, etc ...). When you use the yeoman angular generator you are suppose to run the grunt serve command to start up the angular side. Because I built the app from scratch and I am using npm for my build tool I didn't know how to build the front end server. So, I just went with a simple nginx virtual host pointing to my index.html. Here's the config:
server {
listen 80;
server_name blog.dev;
root /home/michael/Workspace/blog/app;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
I'm not sure what other variables could be affecting the situation, so if I missed something please tell me and I'll be happy to give you what you need!
If you're using the mean stack, you should be able to host both the back end and serve the front end directly with node.
I'm not sure of your project structure but here's the structure for one I'm working on now.
/bin --contains a file called www.js (used to launch app)
/data
/models
/node_modules
/public -- contains my angular implementation
/routes -- contains express routes
/temp
/upload
/views
app.js -- main configuration for express
api.js -- my apis
package.json
in the /bin/www.js file you have the code to start your node server.
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
You'll also need to setup express and your routes so well look at routes first
in the routes directory I have a file called index.js
In this file, I define one route that leads to my angular index.html page.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.redirect('/pages/index.html');
});
module.exports = router;
And of course you'll need to set up express.
process.env.TMPDIR = 'tmp'; // to avoid the EXDEV rename error, see http://stackoverflow.com/q/21071303/76173
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 multer = require('multer');
var flow = require('./flow-node.js')('tmp');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var uuid = require('uuid');
var mongoose = require('mongoose');
var session = require('express-session');
var routes = require('./routes/index');
var app = express();
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(session({genid: function(req) { return uuid.v4()}, secret: 'XXXXXXXXXXX',
saveUninitialized: true,
resave: true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
Now assuming you have your Angular files and javascript in the 'public' directory somewhere, you should be able to start up Node with the following command.
node bin/www
And the point your browser at http://localhost:3000 and be in business.
Hope this helps and happy learning.

ExpressJs - Getting Server Sub-routes to work with Angular factory svcs

For easy maintenance, I would like to compartmentalize my server routes:
server.js (start app):
require('./routes/allRoutes')(app);
allRoutes.js:
module.exports = function(app){
//don't I need to pass (app) below? This will not work as is
var Group1 = require('../routes/Group1/groupRoutes')(app),
Group2 = require('../routes/Group2/groupRoutes')(app);
app.use('/group1', Group1);
app.use('/group2', Group2);
}
groupRoutes.js: (in Group1 Folder)
module.exports = function(app){
//don't I need to pass (app) below? This will not work as is
var SubGroup1 = require('../routes/Group1/subGroup1Route')(app);
.....
app.use('/subgroup1', SubGroup1);
}
subGroup1Routes.js: (in Group1 Folder)
var FooCrtl = require('../../controllers/Group1/subGroup1/FooCtrl');
module.exports = function(app){
app.get('/api/foo', FooCtrl.get);
app.post('/api/foo', FooCtrl.post);
}
AngularJs FooSvcs:
....
return {
getFoo: function(){
return $http({
method: 'GET',
url: '/group1/subgroup1/api/foo', <--- NOT WORKING
});
},
Two-Fold issues:
On the server side do I not need to pass the "app" as a parameter down the routes tree? I tried but recv'd an error.
In the scenario above, what is the correct url for my angular factory as I what have does not work.
OK, this was a tough one but I finally solved it.
My desire to compartmentalize my route structure on the server side to mirror my module structure on the client [angular] side is the right approach.
Where I erred was in thinking I needed to create a tree structure [<-- WRONG] for my server routes and that is NOT the case.
The Example:
Client [angular] side:
public
---- app
---- module A folder
---- module B folder
---- module C folder
Server [express] side structure:
server
---- routes
---- route A folder
--- foo apis
--- bar apis
---- route B folder
---- route C folder
foo api on server side structure:
var express = require('express'),
FooCtl = require('../../controllers/foo/FooCtl');
module.exports = function(app){
app.get('/api/foo', FooCtl.get);
....
}
I do not need to create a "parent route" to collect on my routes in that folder.
Instead, using "npm install --save wrench" in my root, server.js:
var express = require('express'),
path = require('path'),
wrench = require('wrench');
wrench.readdirRecursive("routes", function (error, files) {
if(files != null){
files.forEach(function (file) {
if (file.indexOf('.js') > -1 && file != undefined) {
fullPath = ('./routes/' + file);
console.log(fullPath);
require(fullPath)(app);
}
})} });
And everything works!

Resources