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

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.

Related

Running Express route

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);

Error 404 Node Js heroku app

I am trying to the replicate an example, just change ng-model name, and the url to communicate the client with the server, but that error show up.
Error
POST https://nuevohorario.herokuapp.com/enviarAsignatura 404 (Not Found)
Possibly unhandled rejection: {"data":"<h1>Not Found</h1>\n<h2></h2>\n<pre></pre>\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/enviarAsignatura","data":{"data":"calculo"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Not Found"}
Client -> Front - End
.controller('ctrl-asignatura',function($scope,sk,$http){
$scope.date= new Date();
$scope.data=[];
var vector = [];
$scope.m=function(){
$http.post('/enviar', {data : $scope.asignatura}).then(function(response){
console.log(response);
})
}
sk.on('registrar',function(s){
alert(s);
});
Back End -> Node Js - Socket.IO
var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');
/* GET users listing. */
router.post('/enviar', function(req, res, next) {
console.log(misocket);
misocket.emit("registrar",req.body);
console.log(req.body);
res.status(200).json({
message : "send message"
});
});
module.exports = router;
misocket.js
var i =0;
var ioapp;
exports.connection= function(io){
ioapp=io;
io.on('connect',function(s){
console.log("conetado");
})
}
exports.io=ioapp;
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;
It seems you are useing Router-level middleware
var router = express.Router()
Try to load router-level middleware by using the router.use() functions.
router.use('/enviarAsignatura', function(req, res, next) {
//your code here
}

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);

Express use function

The below code not functioning as expected
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log('first text');
next();
}, function (req, res, next) {
console.log('secondText');
res.end()
}).listen(3000)
app.use([path,] function [, function...])
Mounts the specified middleware function or functions at the specified path. If path is not specified, it defaults to '/' in express documentation but I can't run the second function, not sure why. When I try localhost:3000 in Firefox I receive Cannot GET /
This code is working, but previously it wasn't working:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log("one");
next();
})
.use(function(req,res,next){
console.log("second");
res.end()
})
.listen(3000)
Could it be because of the missing .?
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log('first text');
next();
}, function (req, res, next) {
console.log('secondText');
}).listen(3000) //Was missing a period

express (4.0) custom middleware runs on both instances of router even though it's only declared for one

I'm using the code below to learn a bit about the new express.js (4.0). I can't seem to understand why the logging is happening regardless of which path I hit with my browser. Shouldn't it only log for website.get and not for api.get paths?
// Express 4.0 test...
var express = require('express');
var app = express();
var website = express.Router();
var api = express.Router();
var port = process.env.PORT || 3000;
website.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
website.get('/', function (req, res) {
res.send('Home page');
});
website.get('/about', function (req, res) {
res.send('About page');
});
api.get('/', function (req, res) {
res.send({'json':'response'});
});
api.get('/user', function (req, res) {
res.send({'user':'john'});
});
// app.get('/', function (request, response) {
// response.writeHead(200, {"Content-Type": "text/html"});
// response.end("<h1>Hello, World!</h1>");
// });
app.use('/', website);
app.use('/api', api);
app.listen(port);
console.log('http(s) server revved up on port ' + port);
Any help would rock!
Update: I see, because '/api' matches '/', website gets applied to all routes. Is there any way to avoid this?
probably define the /api router first and the other one - second.
app.use('/api', api);
app.use('/', website);

Categories