Express endpoint not getting called - node.js

An endpoint works fine if added directly to my server.js file:
app.post('/test', function(req,res) {
res.status(200).send({"message" : "OK"});
});
but in an attempt to refactor the app I include a file called api.js from server.js like this:
var routesApi = require('./server/routes/api');
app.use('/v1', routesApi);
and it looks like this:
var express = require('express');
var router = express.Router();
module.exports = function() {
router.post('/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
return router;
}
but if I try and hit this end point the req "stalls" as there is no response. What am I doing wrong?

Because of the way you exported your router, you need to invoke routesApi when adding it to the middleware stack via .use(). This is how that might look like
app.use('/v1', routesApi());
Though you can avoid this altogether by changing your api.js to look like this:
var express = require('express');
var router = express.Router();
router.post('/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
module.exports = router;
and the code for the server can stay the same since now, you're exporting an instance of the Router module.

you have define global variable for app and may use like this:
api.js
exports.allRoutes=function() {
var version1="v1";
app.post('/'+version1+'/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
}
app.js
global.app = express();
var all_routes = require('./server/routes/api');
all_routes.allRoutes();
var server = http.createServer(app);
server.listen(app.get('port'), function(req,res){
console.log('Express server listening on port ' + app.get('port'));
});

Related

How to separate routes from app file in express framework

For example :
server.js file
var express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
routes(app);
app.listen(port);
routes.js file
'use strict';
module.exports = function( app ) {
var api= require('../controllers/apiController');
app.route('/get').get(api.get);
};
apiController.js file
'use strict';
exports.get = function(req, res) {
// console.log( req.app ); // access it but it didn't work ?
// here want to access app to set cookie and changed cookie ?
};
if there is another way please help me thanks :)
If I correct understand your question, with routes you can do something like this:
In routes.js file:
var router = require('express').Router()
router.get('/home', function(req, res, next) {
res.render('index')
})
module.exports = router
In server.js file:
var mainRoutes = require('./routes.js')
app.use(mainRoutes)
Best way (in my opinion) to use controllers from another file it's use exports.functionName notation:
In someController.js file:
exports.homePage = function(req, res) {
res.render('index')
}
So, your router will looks like this:
var router = require('express').Router()
var someController = require('./someController.js')
router.get('/home', someController.homePage)
module.exports = router
Do different way, use route in app.use
app.js:
const
express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
app.use(routes);
app.listen(port);
apiRoutes.js:
const
router = require('express').Router(),
apiController = require('../controllers/apiController');
router.get(
'/get',
apiController.get);
module.exports = router;
Check this example: app.js , some route file

How can I separate route files?

I have a route file in my project and it is called from my app with these lines:
var index = require('./routes/index');
app.use('/', index);
But I need to separate the route file, and I'm trying to do this:
var index = require('./routes/index');
var user = require('./routes/user');
app.use('/', index);
app.use('/user', user);
In route user.js I put the service that I need to access from the client. But it's not working. I don't know what is wrong, I am a beginner in Node.js.
The request returns:
GET /user/find 304 4.203 ms - -
And user.js file is:
var router = express.Router();
router.get('/user/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
*This request works well on index.js
You put user router under /user route, and in your user router you defined app.get('/user/find'), so the actual path would be /user/user/find, you need to remove the user prefix in router
var router = express.Router();
router.get('/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
A simple way to do this can be:
index.js
var express = require('express')
var app = express()
var route1 = require('./route1')
var route2 = require('./route2')
app.use('/', route1);
app.use('/hello', route2);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
route1.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route1');
})
module.exports = router
route2.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route2');
})
module.exports = router
Have you made sure to include a module.exports = router at the end of each of your route files?
Your route files should be set up thusly:
var router = require('express').Router();
router.get("/example", function (req, res) {
res.send("Hello");
});
module.exports = router;

ERROR app.use() requires middleware functions: (so how to set router for app.use in express node.js)?

basically im just trying to seprate routes, models, and controller in node.js application.
i have following files to setup very very basic node.js application.
controller/cv.js
module.exports = {
get: function(req, res, next){
console.log("GET REQUESTS")
next();
}
}
routes/cv.js
var express = require('express');
var CvRouter = express.Router();
var CvController = require('../controller/cv')
CvRouter.get('/', function(req, res, next){
console.log("GET REQUESTS")
next();
})
module.export = CvRouter
app.js
const express = require('express');
const bodyParser= require('body-parser')
var path = require('path')
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
var router = express.Router();
require('./router')(app)
app.listen(3000, function() {
console.log('listening on 3000')
})
router.js
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use([CvRouter]);
};
Basicaly this last file router.js is generting error when i use app.use([CvRouter])
ERROR is: throw new TypeError('app.use() requires middleware functions');
how i can resolve it? i also know its returning object of router. and app.use expecting function in parameter. but how i can achieve my desired MVC pattern of node.js?
as said in comment - you have a typo.
The file routes/cv.js contains module.export instead of module.exports, that makes CvRouter undefined.
Kill the array literal
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use(CvRouter);
};

Express Controller Modularity

New to Node/Express, trying to figure out what the best way to make my server controllers organized and modular. I have app.js file with the following code.
var express = require('express');
var app = express();
// Launch Server
const PORT = process.env.PORT || 8888;
app.listen(PORT, function() {
console.log('Server running on port ' + PORT + '!');
});
// Render Static Views from the Public Directory/Views
app.use('/', express.static(__dirname + '/public/views/'));
// API
// var foo = require(bar);
I want to keep all of my API logic in apiController.js then require it into my app.js. What's the best way to do this?
Example GET Endpoint
app.get('/api', function(req, res) {
res.json({
success: true,
message: 'Hello World!'
});
});
Here is my project structure:
I like David Fang's solution, but I would go one step further and create an Express 4 router for your API routes. They're very composable and modular, as they can act as both routers and middleware, can be nested and imported neatly.
app.js
var apiRouter = require('./controllers/apiController.js');
app.use('/api', apiRouter);
apiController.js
var express = require('express');
var apiRouter = express.Router();
apirouter.get('/some/route', (req, res) => {
// some code...
})
module.exports = apiRouter;
Documentation: http://expressjs.com/en/api.html#router
Here's a simple method:
app.js
require('./controllers/apiController.js')(app);
apiController.js
module.exports = function(app) {
app.get('/api/some/route', function(req, res) {
// some code...
}
}
Maybe this is not the best approach, but I have used it without problem in small apps.
This is how i do it
I have app/controllers/index which call register method each of the controller. Each controller has a register method that register its route with the app.
In controllers:
exports.register = function(app) {
app.post('/login', login)
}
In controllers index.js or routes or whatever you want to name it.
require('../controllers/auth').register(app)
require('../controllers/registration').register(app)
and at the end, drops all other routes to 404.

Expressjs mounting api on different route "Cannot read property 'handle' of undefined"

What I am trying to achieve is my statics being loaded on / , with the api mounted at /api
Here is my main file:
var express = require('express');
var server = express();
var app = require('./api/app');
server.use(express.static('/', __dirname + '/public'));
server.use('/api', app(server));
server.listen(3000);
My app.js file:
module.exports = function(app) {
app.get('/users/:id', function(req, res, next){
res.json(req.params);
});
}
I am getting a Cannot read property 'handle' of undefined error. I still haven't quite got my head around express' use and i'm sure im making a very novice mistake but just not sure how I can configure to get the result I would like.
Thanks.
You should use a Router instead with Express 4.x:
// main.js
var express = require('express');
var server = express();
var api = require('./api/app');
server.use(express.static('/', __dirname + '/public'));
server.use('/api', api());
server.listen(3000);
// ./api/app.js
var router = require('express').Router();
module.exports = function() {
router.get('/users/:id', function(req, res, next){
res.json(req.params);
});
return router;
};
use expects to receive a middleware function, but in this example it's not actually getting anything (notice that there's no return value in app.js). One way to fix this would be to return an instance of express' Router middleware:
var express = require('express');
module.exports = function(app) {
var apiRouter = express.Router();
apiRouter.get('/users/:id', function(req, res, next){
res.json(req.params);
});
return apiRouter;
};

Resources