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'
Related
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);
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
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}`));
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.
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);