express.router throws 404 if routes mentioned in separate file - node.js

I am having trouble and have already spent quite a time to figure out the cause but to no avail. I have researched and feel like I am doing right but obviously I missing out something.
Here is my app.js:
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var bodyParser = require('body-parser');
var session = require('express-session');
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
// tell the app to parse HTTP body messages
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); // read cookies (needed for auth)
//routes
var authRoutes = require('./server/routes/auth');
app.use('/auth', authRoutes);
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000);
});
And here is the separate auth (routes file):
var express = require('express');
var router = express.Router();
router.post('/signup', (req, res, next) => {
console.log("im in");
});
module.exports = router;
After running this, I get 404 response:
POST http://localhost:3000/signup 404 (Not Found)
If I put the routes in app.js file, I get the desired output. Can someone please help me figure out what is that I am doing wrong?

Try http://localhost:3000/auth/signup
app.use('/auth', authRoutes); exposes the authRoutes on paths starting with /auth.

Related

Why doesnot the index route changes not work?

I created a new app using the express generator without any view engine. I go to http://127.0.0.1:3000 which shows the standard express welcome view. Then I add some query params to url like http://127.0.0.1:3000/?test1=testing&test2=testing234 and try to access these in the indexRouter's index.js but cannot access the query params. I tried
req.query.test1
and all other variants nothing works. Then I commented the line
app.use('/', indexRouter);
but I still can access the welcome screen. Commenting the below line throws error which i think is how it works as it is serving a static file.
app.use(express.static(path.join(__dirname, 'public')));
Is there any way I can access the query params in the home url in index router? What am I missing here?
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
indexRouter
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
console.log(req, 'request');
console.log(res, 'response');
res.render('index', { title: 'Express' });
});
module.exports = router;
You can access the req params by commenting out
// app.use(express.static(path.join(__dirname, 'public')));
And, change the response method
Instead of rendering the static file
// res.render('index', { title: 'Express' });
res.send('something');

Having two seperate routes in node/express, where one accepts all the requests

In my node/express app, I have the following app.js file with the following routing
const express = require('express');
const path = require('path');
const logger = require('./middleware/logger');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/wsserver', require('./routes/wsroutes'));
app.use('/', require('./routes/company'));
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log('server runs on port ', port);
});
Every request that goes to http://localhost:8080/wsserver, is handeld by wsroutes. I am planning to setup a websockets server in there, but for now contains
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('ws');
})
module.exports = router;
The / handles all the other requests and its handled by the company that contains
router.get('/',(req, res)=>{ ....
router.get('/:companyName/:id?/:employ?',(req, res)=>{ ...
etc
As you can guess, the problem is that when I go to http://localhost:8080/wsserver, is handled by the / route and the company route. I get the interface and the message no company named wsserver , because the wsserver becomes an argument in the router.get('/:companyName/:id?/:employ?' route.
How can I still have both routes, not change the / one and have them both work correctly? I tried to change positions in the routes like so
app.use('/', require('./routes/company'));
app.use('/wsserver', require('./routes/wsroutes'));
ans still nothing.
What else can I do ?
Thanks

Node express cannot get static file

This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});
Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.

Nodejs Express: Routes in separate files

I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working.
I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.
So this is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');
...
//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//for log requests to console
app.use(morgan('dev'));
app.use('/myRoutes', myRoutes);
app.get('/',function(req,res){
res.end('Welcome Page!');
});
//Server Start
app.listen(port);
console.log('server start at port ' + port);
And the app/routes/myRoutes.js contains the following code:
var express = require('express');
...
var myRoutes = express.Router();
myRoutes.get('/users',function(req,res){
...
});
myRoutes.post('/setup',function(req,res){
...
});
myRoutes.post('/remove', function(req,res){
...
});
module.export = myRoutes;
I also tried this:
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
But again it seems not passing a middleware function.
My second option code
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
is working fine! I just write it in a wrong way
module.export = myRoutes;
isntead of
module.exports = myRoutes;
Hi this is more of additional tips on the question. You main js file would definately need to load a lot of routes and i found importing all of them is a lot of work. Rather use require-dir module to load all the routes like
const loader = require('require-dir');
var app = express();
var routes = loader('./routes');
for (route in routes){
app.use("/"+route,routes[route]);
}
needless to say define all routes inside routes folder and export Router module in each one of them like
var router = express.Router();
router.get(....);
module.exports = router;

App is Running But Not Opening in Browser? It shows Page Not Available

In console it shows message that app/server is running but when I open app in browser it show page not available.
Here's my code for the server initialization (app.js):
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var app = express();
var viewRoute = require('./routes/view'),
apiRoute = require('./routes/api');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', viewRoute);
app.use('/api', apiRoute);
server.listen(9190, function(){
var host = server.address().address,
port = server.address().port;
console.log("Server Running # http:%s:%s", host, port);
});
And my file with the routes (api.js):
var express = require('express');
var api = express.Router();
module.exports = (function() {
api.get('/', function(req, res, next) {
console.log("GET Request for Index Page");
});
api.get('/home', function(req, res, next) {
console.log("GET Request for Home Page");
});
return api;
})();
I've already searched google and every other resources but can't find solution.
It seems you are not sending response back to browser,
in api.js change api.get('/' code to like following:
api.get('/', function(req, res, next) {
res.send("Yes Its working now");
});
You're not sending anything back to the client, so nothing shows up in your browser. Use res.send or similar for this.
I'd suggest to change your code for something like this, and see if this works :
var express = require('express'),
app = exports = module.exports = express();
app.get('/', function (req,res) {
console.log("GET Request for Index Page");
res.send("GET / - 200");
});
app.get('/home', function (req,res) {
console.log("GET Request for home Page");
res.send("GET /home - 200");
});
I removed the exported function immediate call by the way.
I also had same issue, My server was running but i was not able to open my app on browser, Uninstalling skype worked for me.

Resources