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

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.

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

Subdomain routing node.js and express

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

Express body-parser: req.body returns empty object

I've got a simple Express server that uses the body-parser module to access POST-parameters. The app looks like this:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
The problem is that the req.body object is empty (Always returns an empty object {}). Since I already loaded the body-parser middleware I have no idea what else I can try. I hope you have any suggestions.
I used the app Postman for testing. It appeared that it sent the POST data as form-data instead of x-www-form-urlencoded. After changing this setting the data showed up.

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'

Node Js express router not working

js and i am learning node js along with express and I was learning express routing I have following code in rest.js
const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');
const app1 = express();
const server = http.createServer(app1);
app1.get('/api',widgetRouter);
server.listen(3000,function(){
console.log('server started in port 3000');
});
const app = express();
and I also have widgets.js file
const express = require('express');
const widgetRouter = express.Router();
widgetRouter.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
widgetRouter.route("/widgets/:widgetId")
.get()
.put()
.delete();
module.exports = widgetRouter;
but When I try to test the rest api(http://localhost:3000/api/widgets) from postman it says Cannot GET /api/widgets
You have imported and initialized the express module, but then you start a server with the http module. You should use only Express:
Also you should use app.use('/api',widgetRouter) instead of app.get('/api', widgetRouter) which is an express middleware.
const express = require('express');
const app = express();
const widgetRouter = require('./rest/widgets');
app.use('/api', widgetRouter);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000, function(){
console.log('server started in port 3000');
});
You can also try that.
rest.js
const express = require('express');
const http = require('http');
const router = express.Router();
const app = express();
require('./widgets')(app, router);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000,function(){
console.log('server started in port 3000');
});
widgets.js
module.exports = function(app, router){
router.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
router.route("/widgets/:widgetId")
.get()
.put()
.delete();
app.use('/api', router);
});

Categories