Creating a MVC-restful application upon express - javascript

I'm trying create my own application based on rails (not equal, but similar).
So, i'm creating this basic stuff to send to github, so i can use in any project, and i have a problem with my routes.
I am using the express-resource to create the cruds routes.
This is my app.
Controller/example.js:
exports.index = function(req, res, next){
res.send('forum index');
next();
};
exports.new = function(req, res, next){
res.send('new forum');
next();
};
exports.create = function(req, res, next){
res.send('create forum');
next();
};
exports.show = function(req, res, next){
res.send('show forum');
next();
};
exports.edit = function(req, res, next){
res.send('edit forum');
next();
};
exports.update = function(req, res, next){
res.send('update forum');
next();
};
exports.destroy = function(req, res, next){
res.send('destroy forum');
next();
};
exports.load = function(id, fn){
process.nextTick(function(){
fn(null, { title: 'Ferrets' });
});
};
Them in my routes.js:
var express = require('express');
var resource = require('express-resource');
var client = express();
routes.resource('example', require('../controllers/example'));
module.exports = routes;
and my app.js:
// Routes
var routes = require('./routes/routes.js');
app.use('/', routes);
Now the problem:
I can access only the index and the new routes. When i try access:
http://localhost:3000/example - will show right, but with a 304 http code.
http://localhost:3000/example/new - will show right, but with a 304 http code.
http://localhost:3000/example/create - will show the /show/ and a 304 http code.
http://localhost:3000/example/show - will show the /show/ and a 304 http code.
http://localhost:3000/example/edit - will show the /show/ and a 304 http code.
http://localhost:3000/example/update - will show the /show/ and a 304 http code.
http://localhost:3000/example/destroy - will show the /show/ and a 304 http code.
In the terminal, the following error occur:
GET /example/edit 304 1.080 ms - -
Error: Can't set headers after they are sent.
I'm stuck in this.. i dont know the problem. Please, somebody help! haha
Thanks Very Much!

res.send('forum index');
next();
either respond or pass the request along for other middleware to respond, not both.

Replace:
function(req, res, next)
with
function(req, res)
And remove next();
next don't stop a request.
res.send('final output'); // end output
Try:
exports.index = function(req, res){
res.send('forum index');
};
exports.new = function(req, res){
res.send('new forum');
};
exports.create = function(req, res){
res.send('create forum');
};
exports.show = function(req, res){
res.send('show forum');
};
exports.edit = function(req, res){
res.send('edit forum');
};
exports.update = function(req, res){
res.send('update forum');
};
exports.destroy = function(req, res){
res.send('destroy forum');
};
exports.load = function(id, fn){
process.nextTick(function(){
fn(null, { title: 'Ferrets' });
});
};
This is other alternative: https://www.npmjs.com/package/express-enrouten
Check this article (spanish) http://blog.mcnallydevelopers.com/cargar-controladores-de-forma-automatica-en-expressjs-con-node-js/
Rails clone? http://sailsjs.org/

You don't have to call next() while you already called send() the middleware that called by next() trying to call send but couldn't because already sent as the .send() doesn't return and your process keep executing, just remove next()

Related

NodeJS Routing issue

how can I route below url to different view in node.js
http://admin.localhost:3000/users/customer/view
and
http://localhost:3000/users/customer/view
currently it go to the same route that I set for
http://localhost:3000/users/customer/view
App.js
....
var users = require('./routes/users');
app.use('/users', users);
....
Users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Customer/Create', function(req, res, next) {
res.render('customer', {});
});
router.get('/Customer/View', function(req, res, next) {
res.render('customer', {});
});
router.get('/Employee/Create', function(req, res, next) {
res.render('customer', {});
});
router.get('/Employee/View', function(req, res, next) {
res.render('customer', {});
});
module.exports = router;
and what is the terminology for doing something like this with your url by adding admin before url admin.yoururl.com ?
Since you are using express, you can use the express middleware express-subdomain.
The package even supports multi level subdomains like v1.api.domain.com.
You need to create one Router per subdomain and then bind that Router to your express app using the package:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);

NodeJs routing middleware error

I am trying to implement a middleware that will check if a user is authenticated before the server delivers a page. Although it looks like the process of doing this is simple, node is throwing an error which says "Can't set headers after they are sent".
My router's code is:
module.exports = function(app) {
app.get('/', checkAuth, require('./myAuthenticatedPage').get);
app.get('/login', require('./myLoginPage').get);
};
The myAuthenticatedPage.js:
exports.get = function(req, res) {
res.render('index');
};
The myLoginPage.js:
exports.get = function(req, res) {
res.render('login');
};
The checkAuth.js:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
}
next();
}
Any help on this will be greatly appreciated.
Thanks
If you aren't authenticated, you'll redirect the user and then try to render the index page. This causes the http headers to be sent twice, hence the error "Can't set headers after they are sent".
In checkAuth.js try:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
} else {
next();
}
}

Express 4 router.route: route not found

I'm running into a strange issue. The first route is working, but the parameterized route returns a 404 error.
var express = require('express');
var router = express.Router();
router.route('/')
.get(function (req, res, next) {
res.send('A list of vehicles.');
})
.post(function (req, res, next) {
res.send('You added a vehicle!');
});
router.route('/:id')
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
.put(function (req, res, next, id) {
res.send('You edited vehicle: ' + id);
});
If I add this route:
router.route('/test')
.get(function (req, res, next) {
res.send('This is a test.');
});
...I can hit that endpoint. This also seems to work with another router I'm using, which is using router.get(path, function) and router.post(path, function) instead of the router.route(path).get()... methodology.
Am I missing something obvious here? I'm using Express ~4.12.
Gah, I'm an idiot. Just figured this out. I saw an example that used this function signature:
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
This apparently doesn't work. I'm not sure if the http methods check the arity of the function, but this did work:
.get(function (req, res, next) {
res.send('Vehicle: ' + req.params.id);
})
I don't remember where I saw that example, but hopefully this helps someone.

Router.use requires middleware function?

So I'm trying to seperate my login routes in a seperate JS file called login_routes.js
I keep getting this specific error:
TypeError: Router.use() requires middleware function but got a Object
at Function. (/Users/ethanthomas/Desktop/mean-stuff/express-server/node_modules/express/lib/router/index.js:446:13)
Not entirely understanding what it's asking me to implement?
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
server.js:
var express = require('express');
var app = express();
var path = require('path');
var adminRoutes = require('./app/routes/admin_routes');
var loginRoutes = require('./app/routes/login_routes');
app.use('/admin', adminRoutes);
app.use('/login', loginRoutes);
//send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
//start the server
app.listen(1337);
console.log('leet is the magic port');
Your login_routes.js should look something like this (in the context of express):
var express = require('express');
var router = express.Router();
// GET request to /login
router.get('/', function(req, res, next) {
// do something
});
// POST request to /login
router.post('/', function(req, res, next) {
// do something
});
module.exports = router;
In your app.js you use
var login_routes = require('./login_routes');
...
app.use('/login', login_routes);
...
Have a look at the code generated by the express-generator module. That is a starting point for express webserver apps.
People have already offered hints at the solution in comments.
The first issue is that you need to export your "sub" app from login_routes.js. To do so, change this:
var app = express();
Into this:
var app = module.exports = express();
Secondly, you are—probably unintentionally—creating routes for GET /login/login and POST /login/login. To solve this, use this in login_routes.js:
app.route('/').get(...).post(...);
This is because the root path in your sub app (the one in login_routes.js) will get mapped to the path used in app.use() in your main app (server.js).
Do like this:
login_routes.js:
exports.get = function( req, res ) {
res.send('this is the login form');
};
exports.post = function( req, res ) {
console.log('processing');
res.send('proccessing the login form!');
};
server.js:
var loginRoutes = require('./app/routes/login_routes');
app.get('/login', loginRoutes.get);
app.put('/login', loginRoutes.post);
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
module.exports = router;
just writ module.exports = router then it will be work

Unable to do post request on node.js server using express

I have an index.js file which has code to handle get and post requests.
GET request is working pretty fine, the problem is with POST.
here is my code.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
console.log("post request to index");
res.render('index', { title: 'Express' });
});
module.exports = router;
Using Rest client, if I ping my server with a method, i am getting 400 error.
Please help.
Nikhil

Categories

Resources