I am beginner at node.js and express.
In my example project, firstly, I made an express project.
And I want to add a page named /product.
So, I take these steps.
Add product.jade file at views folder.
Add product.js file at routes folder.
revise app.js.
The product.jade is like this.
extends layout
block content
h1 #{title}
p Product Info.
The product.js is like this.
var express = require('express');
var router = express.Router();
/* GET product info. */
router.get('/product', function(req, res, next) {
res.render('product', { title: 'Express' });
});
module.exports = router;
Finally, I revised app.js. I added two lines.
One isvar productRouter = require('./routes/product');,
and the other is app.use('/product', productRouter);.
I was expecting it works.
But when I enter at localhost:3000/product, I only can see 404, Not Found.
Please help. What am I missing?
--- EDIT ---
app.js
var createError = require('http-errors');
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 productRouter = require('./routes/product');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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);
app.use('/product', productRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
You created a route for /product/product because your middleware specifies /product with this line:
app.use('/product', productRouter);
And, then your route again specifies /product in addition to that with this line:
router.get('/product', function(req, res, next) {...}
That creates a route for /product/product.
There are a couple ways to fix this. If your intention is that the productRouter handles all routes that start with /product, then leave the app.use() the same and change from this:
router.get('/product', function(req, res, next) {...}
to this:
router.get('/', function(req, res, next) {...}
If you don't intend to have multiple routes that start with /product and only need to define the one /product route handler, then you don't need to create a whole separate router just for that. You could instead, just export the route handler from product.js (instead of exporting the router) and then just use:
app.get('/product', require('./routes/product'));
That would put just a single route handler in product.js and avoid creating a router for just one route.
Related
I am currently learning how to use nodejs alongside with express as well as ejs. I have a sample app.js file below
var createError = require('http-errors');
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();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
As well as corresponding index.js files in a routes folder in the same directory as app.js. Below is the index.js file:
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;
I have already installed the missing packages by running npm install within the App folder that holds app.js, routes, views as well as other various folders. What am i doing wrong?
I used express-generator to create a new express Project and wanted to add a subrouting system like the following "localhost/" would take me to the index and "localhost/projects" would send "projects page" and "localhost/projects/randomCircles" would send "circles".
Node versión:v10.15.1
Express versión:4.16.0
My Project directory
Also tried to make randomCircles direct route and it worked but i don't get what's the difference
**app.js**:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var projectsRouter = require('./routes/projects');
var circlesRouter = require('./routes/randomCircles');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/projects', projectsRouter);
app.use('/randomCircles', circlesRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
**index.js**:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'ProjectManager',menu: ['About Me','Projects','Contact Me']});
});
module.exports = router;
**project.js**:
var express = require('express');
var router = express.Router();
/* GET projects list. */
router.get('/', function (req, res, next) {
res.send('projects page');
});
router.get('/randomCircles', function (req, res, next) {
res.send('circles');
});
module.exports = router;
**randomCircle.js*:
var express = require('express');
var router = express.Router();
/* GET project randomCircles. */
router.get('/', function(req, res, next) {
res.render('randomCircles', {title: 'randomCircles'});
});
module.exports = router;
Routes that work:
localhost/
localhost/randomCircles
Routes that don't work:
- localhost/projects
- localhost/projects/randomCircles
I should be able to access "localhost/projects" but i get this error:
Not Found
404
NotFoundError: Not Found
at C:\Users\josea\Documents\MEGAsync\coding\projectManager\app.js:27:8
at Layer.handle [as handle_request] (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:317:13)
at C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:275:10)
at C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:635:15
at next (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:260:14)
at Function.handle (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\josea\Documents\MEGAsync\coding\projectManager\node_modules\express\lib\router\index.js:47:12)
There was a typo in the routing system, edited the code of the post and now it works just fine <3
You also need to use app.listen
While configuring your routers is necessary to have a functional Express app, you also need at some point to listen for incoming requests. Somewhere in your main server starting point, do this
To import and integrate a router you defined in another file, first import it. Then add it using app.use(myOtherRouter)
const express = require('express')
const app = express()
const port = 3000
// Import your other router(s)
const someRouter = require('./myOtherRouter');
app.use(someRouter);
// Listen for incoming requests
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I generated a project with express-generator.
In my routes directory, i have 2 files : index.js and users.js, and about.js that handles the /about route.
Accessing /about results in Error 404 : Page Not found.
When adding the handler for /about in app.js, the error was gone.
./app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index')
var aboutRouter = require('./routes/about');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/about', aboutRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development\
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
./route/index.js:
var express = require('express');
var app = express();
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.json( {
message : "Home Page (Requeste for list)",
method : req.method,
Succes : "True"
});
// res.render('index', { title: 'Express' });
})
module.exports = router;
./routes/about.js:
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res) {
res.send('im the about page!');
});
router.post('/about', function(req, res) {
res.send('im the about page!');
});
module.exports = router;
Rewrite your router/about.js like this
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('im the about page!');
});
router.post('/', function(req, res) {
res.send('im the about page!');
});
module.exports = router;
Since in your app.js, you already declare the prefix /about at line 24, so you do not have to do it again in router/about.js
What is happening is that in app.js you have set the root for about rout as "/about" and inside "about.js" you have specified router.get('/about') again, what will result in, for accessing the about route having to use /about/about (you may try before fix it). For you to get the result that you are expecting you should use router.get(´/´) inside about.js and in app.js keep as it is app.use('/about', aboutRouter);. You can have a look at https://expressjs.com/en/guide/routing.html for more information. Regards.
I'm trying to build a configurable middleware (a custom middleware function that takes custom parameters, and returns a (req,res,next) function that uses these parameters) in Express. However, I can't get this middleware to execute on a router.get() call.
The expected behaviour in the code below is that, when trying to GET the home page (/), the console logs 'success!' then I get a 404 (as the next() in the middleware will pass me on to the 404 function).
However, nothing happens and the request times out. The function is being detected, as when I put the console.log() in the middleware but just before the return function(req,res,next){ line, I am seeing the output on the console. I only get this issue when the configurable middleware is returning a function.
./app.js (no changes to the template that Express builds):
var createError = require('http-errors');
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();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
./routes/index.js:
var express = require('express');
var router = express.Router();
var simplemiddleware = require('../middlewares/simplemiddleware');
/* GET home page. */
router.get('/', function(req, res, next) {
simplemiddleware.simpleReturn('success!');
});
module.exports = router;
./middlewares/simplemiddleware.js:
exports.simpleReturn = function (outputString){
return function (req,res,next) {
console.log(outputString);
next();
}
}
Please note that the
var simplemiddleware = require('../middlewares/simplemiddleware');
actually is a function, to fix the problem, please try the following.
./routes/index.js:
var simplemiddleware = require('../middlewares/simplemiddleware');
/* GET home page. */
router.get('/', function(req, res, next) {
// note `simplemiddleware.simpleReturn(str)` returns a function
let func = simplemiddleware.simpleReturn('success!');
// run the middleware
func(req, res, next);
});
I am trying to use EJS but whenever res.render is called, it just hangs there with no response.
This is my app.js file
var express = require('express');
var bodyParser = require('body-parser')
var mongoose = require('mongoose');
var app = express();
var router = require('./router/index')(app);
app.use(bodyParser.json())
app.set('view engine', 'ejs');
// Internal Server error
app.use(function(err, req, res, next) {
res.status(err.status || 500);
});
module.exports = app;
app.listen(8888);
And in my routes file
module.exports = function (app) {
app.use('/', require('./routes/Website'));
app.use('/api/users', require('./routes/UsersRoute'));
app.use('/api/keys', require('./routes/KeysRoute'));
};
And in the website file
var express = require('express');
var router = express.Router();
// Get all Users data
router.get('/', function (req, res) {
res.render('index', { title: 'The index page!' })
});
I have a index.eps file in views folder and a layout.eps in the layout folder. What am i doing wrong in this?
Should your internal server error middleware have a conditional?? It seems to me that it would try to send the response from your middleware every time a route is called.
Try commenting out the res in your middleware and try calling next();
Solved the problem by removing
// Internal Server error
app.use(function(err, req, res, next) {
res.status(err.status || 500);
});
And seems like EJS looks for views folder in the root directory instead of the directory of the .js file