Running Express route - javascript

I have the following snippet of code and when I access the local host I get an error: Cannot GET /
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.send("function has started");
});
express().listen(3001);
module.exports = router;

var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
app.listen(3001)
This should be fine

If you want to use the router, you need to use the use method example (app.use('/', router):
var express = require('express');
var router = express.Router();
var app = express()
/* GET home page. */
router.get('/', function (req, res, next) {
res.send("function has started");
});
app.use('/', router)
app.listen(3001);

Related

How to pass DB object in multi router setting in ExpressJS?

I would like to make multiple router settings like the example in ExpressJS Doc.
I have index.js , api1 , api2 like below.
How can I pass the db object from index.js to api1 and api2?
I try with
app.use('/api/v1', require('./controllers/api_v1')(db));
but it shows errors:Router.use() requires a middleware function but got a Object
index.js:
var express = require('../..');
const knex = require('knex');
const config = require('./config');
var app = module.exports = express();
const db = knex(config.db);
app.use('/api/v1', require('./controllers/api_v1'));
app.use('/api/v2', require('./controllers/api_v2'));
app.get('/', function(req, res) {
res.send('Hello from root route.')
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
api_v1.js
var express = require('../../..');
var apiv1 = express.Router();
apiv1.get('/', function(req, res) {
res.send('Hello from APIv1 root route.');
});
apiv1.get('/users', function(req, res) {
res.send('List of APIv1 users.');
});
module.exports = apiv1;
api_v2.js
var express = require('../../..');
var apiv2 = express.Router();
apiv2.get('/', function(req, res) {
res.send('Hello from APIv2 root route.');
});
apiv2.get('/users', function(req, res) {
res.send('List of APIv2 users.');
});
module.exports = apiv2;
You could export the db object from a database.js file and require it in the index.js file as well as every other file where you need database access. Or, an easier but uglier method, would be to make the variable global via global.db = db. You could then use db everywhere in your Node.JS application.

redirect to different controller dependant on Url

Ok so I'm trying to redirect the request to a different controller depending on the URL.
My server.js :
const express = require('express');
var app = express();
var router = express.Router();
// controllers
var { loginController } = require('./controller/loginController');
// Specify routes
app.use('/test', loginController);
app.listen(3000, () => {
console.log('started on port 3000');
});
module.exports = { app }
Now if the URL is /test then I would like to redirect the request to loginController, inside loginController I have the following:
const express = require('express');
var router = express.Router();
router.get('/', (req, res) => {
res.send('inside logincontroller');
});
Very short and sweet, however when I run node server.js I get the following error message: Router.use() requires middleware function but got a undefined now I've gone through the Router Use but I'm slightly confused (newbie) I don't have any middleware at present.
Would someone be able to explain to me how I go about redirecting the request to the loginController when the url is /test
server.js
const express = require('express')
// Controllers
var loginController = require('./controller/loginController')
var app = express()
// Specify routes
app.use('/test', loginController)
app.listen(3000, () => {
console.log('started on port 3000')
})
loginController.js
const express = require('express')
var router = express.Router()
router.get('/', (req, res) => {
res.send('inside logincontroller')
})
module.exports = router
Then if you visit http://localhost:3000/test will get the output 'inside logincontroller'

Unexpexted 404 in express.js

I really don't understand why node(express) just render index page and return 404 for other pages ("comproAffitto" in the example).
app.js
var index = require('./routes/index');
var comproAffitto= require ('./routes/comproAffitto');
...
...
app.use('/', index);
app.use('/comproAffitto', comproAffitto);
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;
routes/comproAffitto.js
var express = require('express');
var router = express.Router();
/* GET comproAffitto page. */
router.get('/comproAffitto', function(req, res, next) {
console.log("dentro");
res.render('comproAffitto', { title: 'Exprrress' });
});
module.exports = router;
html href
<a href="/comproAffitto/" class ....
console log
GET /comproAffitto/ 404
where is the problem?
thank you all
You are constructing the path two times: /comproAffitto/comproAffitto.
You should remove one of them or here:
app.use('/', comproAffitto);
or there:
routes/comproAffitto.js
var express = require('express');
var router = express.Router();
/* GET comproAffitto page. */
router.get('/', function(req, res, next) {
console.log("dentro");
res.render('comproAffitto', { title: 'Exprrress' });
});
module.exports = router;
leaving app.use('/comproAffitto', comproAffitto);
You defined /comproAffitto/comproAffitto instead of /comproAffitto
You would need to either change this:
app.use('/comproAffitto', comproAffitto);
to this:
app.use('/', comproAffitto);
or this:
router.get('/comproAffitto', function(req, res, next) {
to this:
router.get('/', function(req, res, next) {

Why the subdomains are not working with express.js?

so I am experimenting with it locally, this is in my hosts file
127.0.0.1 example.dev
127.0.0.1 www.example.dev
127.0.0.1 api.example.dev
and this is my code:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
// example.com
app.get('/', function(req, res) {
res.send('Homepage');
});
//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);
it's basically the example from the package website
api.example.dev/users works well, but when I go to to api.example.dev the content is the same as on example.dev (like it is overwritten)
any ideas what I am doing wrong?
thanks
This is a order of requests processing problem. Move the declaration of the request handler for the main domain after the subdomain:
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));
// example.com
app.get('/', function(req, res) {
res.send('Homepage');
});
app.listen(3000);

Using different router for different subdomains in node.js with express

I want to use different routes in my app, depending on the subdomain in req.headers.host.
So I came around with this idea (extremely simplified example):
var express = require('express');
var domain1 = require('./routes/domain1');
var domain2 = require('./routes/domain2');
var app = express();
app.use('*', domainRouting);
function domainRouting(req, res, next){
var subdomain = req.headers.host.split('.')[0];
if(subdomain === 'domain1'){
app.use(domain1);
}
else{
app.use(domain2);
}
next();
}
//404 handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
res.send('error');
});
var server = app.listen(3001, function() {
console.log('Listening on port %d', server.address().port);
});
domain1.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('DOMAIN 1: ' + req.url);
});
module.exports = router;
domain2.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('DOMAIN 2: ' + req.url);
});
module.exports = router;
But this does not work, the routes are ignored and the request jumps into the last 404-handler.
Any ideas for this?
You can't use app.use() dynamically like that within a middleware. You might call your router directly with domain1(req, res, next) instead of app.use(domain1).
Or you might look into using a module like subdomain to make it easier to handle subdomains in Express.

Categories