Subdomain routing node.js and express - javascript

I am trying to make a site where the code checks what subdomain the user is accessing from. I can get the host by running this:
app.get('/', (req, res) => {
const host = req.get('host');
const origin = req.get('origin');
res.send(host)
})
And i get the result: localhost:5000.
But i want to make it so that if the user is accessing from domain1.com it uses one router, and if it is from domain2.com it uses another. here is the code im trying to use:
server.js
const express = require('express')
const app = express()
const router = express.Router();
app.set('view engine', 'ejs')
app.get('/', (req, res) => {
const host = req.get('host');
const origin = req.get('origin');
if(host === "domain1.com:5000"){
const test = require('./routes/test.js')
app.use('/', test)
}else if(host === "domain2.com:5000"){
res.send("Domain2")
}else{
res.send(host)
}
})
app.listen(5000)
/routes/test.js
const express = require('express')
const router = express.Router()
router.get('/', async (req, res) => {
res.send("it Works")
})
module.exports = router
When i try accessing the domain1 it does not work, and i don't get any errors in console

Related

Node.js Error: Cannot GET/ from running on the web browser

So here I have 2 route files and 1 controllers for each.
My first router that is root, is working fine !
but my second route that is /teacher is giving me this error "Cannot GET /teacher"
I literally copy pasted the root route code and changed the variable names still its not working.
following are my files:
server.js
const express = require('express');
const dotenv = require('dotenv');
const root_rt = require('./routes/root-rt');
const teacher_rt = require('./routes/teacherlogin-rt')
dotenv.config();
const uri = process.env.DB_URI;
const port = process.env.PORT;
const app = express();
app.use(express.json());
app.get('/', root_rt);
app.get('/teacher', teacher_rt);
app.listen(port, () =>{
console.log(`server started on http://localhost:${port}`);
});
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.route('/')
.get(teacherController.login);
module.exports = router;
teacher-cnt
module.exports.login = function (req, res) {
res.send('this is teacher login page');
};
Thank you in advance.
When using routers, you shouldn't use app.METHOD() to mount them, but app.use():
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
Make the below change in your teacherlogin-rt.js, it will start working
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.get('/', teacherController.login);
module.exports = router;
server.js
app.use('/', root_rt);
app.use('/teacher', teacher_rt);

Making a signup form and login form using express server

So I am basically making a simple website on my localhost that has a signup form and some other html elements. I managed to setup the signup process smoothly. So when the user fills in the form and submits it to the root route("/"), an email is sent to the subscriber containing a random password using nodemailer and then the password is to be used to login to the user dashboard. The whole data is submitted as a mongodb document which I had setup. Upto this the process goes smoothly and when the user does the signup, the mail is sent to the subscriber's email id and then they are redirected to the login page. So now I am confused about setting up the server.
// index.js file
const express = require("express");
const app = express();
const port = 5000;
const mainApp = require("./main.js");
const loginApp = require("./login.js");
app
.use(function (req, res, next) {
if (req.hostname == "http://localhost:5000") {
mainApp(req, res, next);
console.log("main");
} else if (req.hostname == "http://localhost:5000/login") {
loginApp(req, res, next);
console.log("login");
}
})
.listen(port, () => console.log(`App listening on port: ${port}`));
I don't understand how can I import the whole main.js module(the root route where the signup form exists, and the form data is also posted to the root route) and the login.js module(the '/login' route where the login form exists.
How can I make index.js run both modules on the same port?
You have two options to achieve what you need:
Using app.METHOD(PATH, HANDLER). Read more ExpressJs routing basic
// index.js file
const express = require("express");
const app = express();
const port = 5000;
const mainApp = require("./main.js");
const loginApp = require("./login.js");
// route for /
app.get("/", function(req,res, next) {
mainApp(req, res, next);
console.log("main");
});
// route for /login
app.get("/", function(req,res, next) {
loginApp(req, res, next);
console.log("login");
});
app.listen(port, () => console.log(`App listening on port: ${port}`));
Using express.Router. This enables to break routing logic into modules. Use this option to handle routing in modules Main.js and login.js
// main-router.js
var express = require('express')
var router = express.Router()
const mainApp = require("./main.js");
// handler for /
router.get('/', function (req, res) {
mainApp(req, res, next);
console.log("main");
});
module.exports = router
import module in index.js
const express = require("express");
const app = express();
const port = 5000;
const mainRouter = require("./main-router.js");
const loginApp = require("./login.js");
// route for /
app.get("/", mainRouter);
// route for /login
app.get("/", function(req,res, next) {
loginApp(req, res, next);
console.log("login");
});
app.listen(port, () => console.log(`App listening on port: ${port}`));

Why does my express router not respond to my get request?

So i have made a simple express app, but i have been trying for several hours to get a response to a simple get request when i visit http://localhost:3000/
This is my app.js
// IMPORTS
const express = require('express')
const mongoose = require('mongoose')
const customerRouter = require('./routes/customerRoute.js')
const app = express()
const PORT = 3000
// CONNECTION
mongoose.connect('mongodb://localhost/Customers', {useUnifiedTopology: true })
mongoose.connection.on('open', () => {console.log('Connected to database.')})
//APP USE ROUTES AND JSON
app.use(express.json)
app.use('/customers',customerRouter)
app.get('/', (req, res) => {
res.send('Home')
})
// APP PORT SET
app.listen(PORT)
console.log('Server started on port 3000')
This is my routes file
const express = require('express')
const router = express.Router()
console.log('into the router')
router.get('/', (req, res) => {
console.log('GET request')
})
module.exports = router
Substitute app.use(express.json) with app.use(express.json()) and everything will work. You have a mistake in this middleware that parses incoming requests with JSON payloads.
Source: express docs
You made a mistake in middleware app.use(express.json()) is a function not a property of the express object.

cannot GET / when serving Angular app using express and nodejs

I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html

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'

Categories