I used express-generator and the following are 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 cors = require('cors');
var app = express();
app.use(cors());
// 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')));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
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;
And when access to http://localhost:5000/api/ got Error:
Not Found
404
NotFoundError: Not Found
at D:\_projects\booking-system\api\app.js:28:8
at Layer.handle [as handle_request] (D:\_projects\booking-system\api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\_projects\booking-system\api\node_modules\express\lib\router\index.js:317:13)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:335:12)
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:275:10)
at D:_projects\booking-system\api\node_modules\express\lib\router\index.js:635:15
at next (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:260:14)
at Function.handle (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:174:3)
at router (D:_projects\booking-system\api\node_modules\express\lib\router\index.js:47:12)
Following is routes/index:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Thank you very much for your helps !
The issue is that you define a GET / route in your routes/index.js file and then register it as app.use('/', indexRouter) in your app.js.
So you either change your routes/index.js file to it looks like this:
var express = require('express');
var router = express.Router();
// Note the /api
router.get('/api', function(req, res, next) {
res.render('index', { title: 'API' });
});
module.exports = router;
Or you keep routes/index as it is but your change the way your register it in your main.js to this:
// ...
// Note the /api
app.use('/api', indexRouter);
app.use('/users', usersRouter);
// ...
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'm setting up a new server with node js and the framework express (Version 4.16). I want to route my Rest-Endpoints. In my route.js-file i want to call a function from app.js(my Server), but getting a Typeerror where the function, that i want to call from another file, is not a function.
Error:
TypeError: callFunction.getDataFromDb is not a function
at C:\Users\---\WebstormProjects\pwa_node_server\routes\recipes.js:7:18
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\---\WebstormProjects\pwa_node_server\node_modules\express\lib\router\index.js:47:12)
My server:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var axios = require('axios');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipesRouter = require('./routes/recipes');
var cors = require('cors');
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(cors({credentials: true, origin: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/recipes', recipesRouter);
// app.use('/poste-dein-rezept', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log("catch404");
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');
});
var getDataFromDb = function (res) { // This function to call in another file
};
module.export = {
getDataFromDb
};
module.exports = app;
My route-file:
var express = require('express');
========
var router = express.Router();
var callFunction = require('../app');
router.get('/', function(req, res, next) {
console.log('Recipes-Endpoint received Request');
callFunction.getDataFromDb(res);
});
module.exports = router;
I just want to call a function from another file.
You're using module.export. The Correct property name is module.exports, which you are also using.
One way to solve this is:
app.getDataFromDb = getDataFromDb;
module.exports = app;
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.
for my app i use node.js as backend and Express as framework. I use Netbeans as IDE and i get the following output.
Not Found
404
Error: Not Found
at /home/ingeborg/netbeans/GML/app.js:33:13
at Layer.handle [as handle_request] (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:317:13)
at /home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:335:12)
at next (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:275:10)
at /home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:635:15
at next (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:174:3)
at router (/home/ingeborg/netbeans/GML/node_modules/express/lib/router/index.js:47:12)
I have the following data setup:
- node-modules
- public
- fonts
- images
- javascripts
- stylesheets
stylesheets.less
stylesheet.css
- routes
index.js
news.js
users.js
- views
index.jade
error.jade
news.jade
layout.jade
Gruntfile.js
app.js
gulpfile.js
package.json
the app.js looks like this
var news = require('./routes/news');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...
app.use('/', index);
app.use('/index', index);
app.use('/news', news);
app.use('/users', users);
and this is my index.jade
h3
a(href="news") link
and this my news.jade
h3 test
.
The routing is realised over route files.
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/index', function(req, res, next) {
res.render('index');
});
module.exports = router;
the news.js router file is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('news', function(req, res, next) {
res.render('news');
});
module.exports = router;
The following circumstances are
the routing on the links "/" and "index" works as wanted.
the routing on "/news" or "news" (tested in the rounting, app.js and view file) not. I have no clue why the routing isn't working. I hope i haven't forgotten sth.
Thx,
Inge
Your code works for me.
/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 index = require('./routes/index');
var news = require('./routes/news');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//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('/', index);
app.use('/users', users);
app.use('/news', news);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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/news.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('news');
});
module.exports = router;
The news route file is missing. There you have to render your jade.
var news = require('./routes/news');