I have this ships.js in my routes folder:
var express = require('express');
var router = express.Router();
/* GET Ships page. */
router.get('/ships', function(req, res, next) {
res.render('ships', { title: 'Express' });
});
module.exports = router;
And I have these to statements in my app.js:
var routes = require('./routes/index');
var users = require('./routes/users');
var ships = require('./routes/users');
and
app.use('/', routes);
app.use('/ships', ships);
app.use('/users', users);
However if I navigate to localhost:3000/ships I receive the following message:
respond with a resource
Sorry have read the docs, just not to snazzy with express.
You have two errors in you app module:
1.Invalid require call for ships route:
var ships = require('./routes/users'); <--
// should be:
var ships = require('./routes/ships');
2.Invalid router using in app.use:
app.use('/ships', ships);
// should be:
app.use(ships); // and the same for others
Related
I am trying to centralize all of my route file into a index file and place that index route file in my main app file. I am trying to follow this thread
I have added app.js file. And the routes/ folder below:
When i am trying to get any of the url as mentioned below, it's showing the 404 error.
app.js:
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
routes file:
-- index.js
-- author.js
-- book.js
index.js:
const express = require('express');
const router = express.Router();
// Get Home Page of The Web Application
router.get('/', function(req, res) {
res.send('Library Home Page');
});
router.use('/author', require('./author').router);
router.use('/book', require('./book').router);
module.exports = router;
author.js:
const express = require('express');
const router = express.Router();
var AuthorController = require('../controllers/authorController');
router.get('/', AuthorController.authorList);
router.get('/:id', AuthorController.authorDetail);
router.get('/create', AuthorController.authorCreateForm);
module.exports = router;
book.js:
const express = require('express');
const router = express.Router();
var BookController = require('../controllers/bookController');
router.get('/', BookController.bookList);
router.get('/:id', BookController.bookDetail);
router.get('/create', BookController.bookCreateForm);
module.exports = router;
I want to access the url as follows:
Home:
/
Author:
/author/
/author/1
/author/create
Book:
/book/
/book/1
/book/create
module.exports = router is a default export so require('./author').router refers to an undefined property on the router, it should be:
router.use('/author', require('./author'));
And in your server entry:
app.use(indexRouter); // No `'/'` as first param
I have issue setting up routes for user in below code, I want to use express middleware and trying routes using app.use.
index.js is invoking user controller method once api's is being called So in below code i am trying to post data api/users from client but it returns 404.
How can i fix this issue using below routes setup ?
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
require('./config/express')(app);
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
app > routes.js
module.exports = function(app) {
app.use('api/users', require('./api/user'));
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
// res.sendFile(path.join(__dirname, ''../public/views/index.html''));
});
};
config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
// import cookieParser from 'cookie-parser';
// import errorHandler from 'errorhandler';
var path = require('path');
// import lusca from 'lusca';
var config = require('./db');
var mongoose = require('mongoose');
//var mongoStore = connectMongo(session);
module.exports = function(app) {
// app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
}
User index where i will handle all crud operation for user
app > api > user > index.js
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
router.get('/', controller.index);
router.post('/',controller.create);
module.exports = router;
1st:
To handle all request
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
app.use(function(req,res)
{
res.sendfile('./public/views/index.html');
console.log("Not found....I will handle *unhandle* rout here for you");
})
// app.get('*', function(req, res) use the above function instead of this
But this function at the end so it will only excute when no route path found to the app object.
Express documentation
2nd:
To handle createuser
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
// you must define route which you want to handle in user file
router.get('/api/user', controller.index);
router.post('/',controller.create);
module.exports = router;
Update working example with some explanation
Your app.js file
var express=require('express')
var app=express()
app.use('api/user',require('./user'))
app.use('/',require('./user'))
app.use(function(req,res)
{
res.sendfile('stack10.html')
console.log("Not found....I will handle *unhandle* rout here for you");
})
app.listen(8080,function()
{
console.log("server listening on port 8080")
})
user.js
var express = require('express')
var router = express.Router()
var app=express()
router.get('/api/user', function(req, res) {
res.send('respond for ..../api/user')
});
router.get('/',function (req,res) {
res.send('respose for ..../')
})
module.exports = router;
Your app.use will be app.use(api/user) while in user will be router.get(/api/user) so when u try http://127.0.0.1:8080/api/user
your response will be respond for ..../api/user
I want to make a change from the actual structure of my code. This is the actual code i have:
//index.js
var routes = require('./routes');
var subdomain = require('express-subdomain');
//require express app with settings
var app = require('./app');
//export the application
module.exports = app;
// routes request like endusers-api.mydomain.ext/
app.use(subdomain('endusers-api', routes.apis.endusers));
// routes request like mydomain.ext/
app.use(routes.webapps.endusers);
//routes/index.js
var apis = {endusers: require("./apis/endusers")}
var webapps = {endusers: require("./webapps/endusers")}
var routes = {apis: apis, webapps: webapps}
module.exports = routes;
//routes/apis/endusers
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-api-access"), function(req, res, next) {
res.json({
"name" : "Endusers API"
});
});
module.exports = route;
//routes/webapps/endusers.js
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-webapp-access"), function(req, res, next) {
res.render('endusers/index', {title: 'Homepage'});
});
module.exports = route;
Now I want to change the above code to this (feel free to tell me if this is a good approach of doing things in Node.js or not):
//index.js
var middlewares = require('./middlewares');
var app = require('./app');
module.exports = app;
//i want to change to this
app.use(middlewares.endusersApi);
app.use(middlewares.endusersWebapp);
//Stuff for creating server and listening...
//middlewares/index.js
var middlewares = {
endusersApi : require("./apis/endusers"),
endusersWebapp : require("./webapps/endusers")
}
module.exports = middlewares;
//middlewares/apis/endusers.js
//TODO
//middlewares/webapps/endusers
//TODO
How should I write the TODO portions above. It look like we will need nested middlewares (a middleware calling another middleware). Please, your suggestions.
I found the answer using by express.Router().all() method.
//middlewares/apis/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/',subdomain('endusers-api', routes.apis.endusers));
//the two next lines are alternatives to the line above
//middleware = subdomain('endusers-api', routes.apis.endusers); //can assign only one route
//middleware.use(subdomain('endusers-api', routes.apis.endusers)); // can use many routes
module.exports = middleware;
//middlewares/webapps/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/', routes.webapps.endusers);
//the two next lines are alternatives to the line above
//middleware = routes.webapps.endusers; //can assign only one route
//middleware.use(routes.webapps.endusers); // can use many routes
module.exports = middleware;
very new to nodejs here. I've tried to put routes in app.js without problem. However, after moving all the routes to a separate file under PROJECT_DIR/src/routes/index.js, and then I open the page in browser it says "Cannot GET /wines". Here's code in app.js and src/routes/index.js:
// app.js
var express = require('express');
var app = express();
var path = require('path');
global.app = express();
require('./src/routes/index');
// also tried: require(path.join(__dirname, './src/routes/index'));
global.server = app.listen(3000, '0.0.0.0', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// ./src/routes/index.js
// tried console.error(app); and it printed all the stuff about app in the server log
app.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
I'm sure I'm missing something. Any help is appreciated!
Problem
Honestly, I am not sure why what you are doing does not work.
The file can be found because otherwise, Node would throw an error, and the fact that you can access app from the routes file means app is accessible.
I have a suspicion that this may be due to garbage collection -- because you do not hold a reference to the module, it may be preemptively destroyed.
What's more, there is a construct in Express called a router that probably exists for this exact purpose.
Solution
While I'm not sure about the problem I am sure about the solution -- use a router, like this:
var express = require('express');
var router = express.Router();
router.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
And then in your app.js file, do this:
var routes = require('./routes/index');
app.use('/', routes);
Another benefit of routers is that you do not have to pollute the global object anymore..
You need to use export in index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
and use it like this in app.js
var router = require('./src/routes/index');
The express generator creates an app like this:
in the main app.js:
var app = express();
//...
var routes = require('./routes/index');
app.use('/', routes);
//...
in routes/index.js
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;
What is the best way to use variables that I define in app.js in the index.js?
For example, before defining the routes, I set up the mongoose model:
var myModel;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function (callback) {
//load schemas
var dbSchema = require('./schema');
myModel = mongoose.model('mymodel', dbSchema.myModel);
});
How can I use 'myModel' in the routes module?
You should define your models outside app.js, in their own separate files for each separate model, and export that model which you can then require in various places you need it. Your model definition doesn't actually need to be inside db.once('open'
For example: if you have a model User you should define it in its own file like this:
db/user.js
var mongoose = require('mongoose');
var schema = mongoose.Schema({
…
});
var model = mongoose.model('user', schema);
module.exports = model;
This way if you want to use the User model inside your routes/index.js:
…
var User = require('../db/user');
router.get('/user/:id', function(req, res, next) {
User.findById(req.params.id, function(err, user){
res.render('user', { title: 'Express', user: user});
});
});
Pass it as a parameter when you require your router in your app.js file. You're going to have to slightly modify your index.js file
var express = require('express');
var myRouter = function(myModel) {
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// You can use your myModel model here
return router;
}
module.exports = myRouter
Now inside your app.js
var app = express();
//...
// Pass myModel as a parameter
var routes = require('./routes/index')(myModel);
app.use('/', routes);
//...