EJS render no output - node.js

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

Related

routing in nodeJs - What could be the reason my routing is not working?

I managed my routing via a few routers, but something went wrong,
when i try to call a functton i get the error:
Error: No default engine was specified and no extension was provided.
I can't understand what could be my problem..
I would be greatfull if soembody can help
my code:
// index.js
const express = require("express");
const router = express.Router();
const userRouter = require("./userRouter");
const qeustionRouter = require("./questionRouter");
const questionToTestRouter = require("./questionToTestRouter");
const testRouter = require("./testRouter");
const subjectRouter = require("./subjectRouter");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("index", { title: "Express is run" });
});
router.get("/user",userRouter);
router.get("/qeustion",qeustionRouter);
router.get("/questionToTest",questionToTestRouter);
router.get("/test",testRouter);
router.get("/subject",subjectRouter);
module.exports = router;
another router for example:
// userRouter.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
router.post('/signUp', userController.signUp)
router.get('/login', userController.login)
router.delete('/deleteStudent', userController.deleteStudent)
router.delete('/deleteTeacher', userController.deleteTeacher)
router.get('/getAllUsers', userController.getAllUsers)
router.get('/getStudentsByTeacherId/:teacherId', userController.getStudentsByTeacherId)
router.get('/getTeachersByStudentId/:userId', userController.getTeachersByStudentId)
router.post('/updateUser', userController.updateUser)
module.exports = router
// app.js
var express = require("express");
var cors = require("cors")
const mongoose = require('mongoose');
//var path = require("path");
// var favicon = require("serve-favicon");
// var logger = require("morgan");
// var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var routes = require("./routes/index");
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(cors());
app.use("/", routes);
//--------------------------------------
//listen to localhost
app.listen(4000, (req, res) => {
console.log("listening on port 4000");
})
//--------------------------------------
//connect to mongo//
const connectionParams = {
useNewUrlParser: true,
// useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(process.env.DB_CONNECT, connectionParams)
.then(() =>
console.log("connected to mongo"))
.catch((error) =>
console.log("error: " + error))
// 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 handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err,
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {},
});
});
module.exports = app;
I think you need a view engine. I see you are defining "jade" as your view engine but it is commented out and it is not in the index.js
please make sure you installed jade package. You can check this by looking at your package.json file.
npm install jade --save
You need to define jade as your view engine (in the index.js) and your jade files must be stored inside the views folder. Inside index.js file, you can change all router keywords to app
const express = require ("express");
const app = express ();
app.set("view engine","jade")
And delete this: const router = express.Router();
And this folder must be placed at the root of your project (in other words, your index.js file and "views" folder should be at the same level). If you do it in this way, you wont need to define a path route.
I kindly advise you to use "ejs" as your view engine. It is more common than "jade". You can create ejs files easily, just like an html page.
And first start with a single route to test if your express framework is working. You can then gradually add up other routes. And please let me know if this answer helps, otherwise I will delete.

How to get data in express js

For the first time ever i am trying to understand expressJs and I have testing route which returns simple test sentence as JSON, but i can't get in in expressJs.
test.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('https://mysite.ccc/api/test', function(req, res, next) {
res.json(data)
});
module.exports = router;
apps.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 testRouter = require('./routes/test'); ////////////////////////////////////////////////////////here
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('/test', testRouter); ////////////////////////////////////////////////////////here
// 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;
I'm not sure but i guess it suppose to show my api sentence in http://127.0.0.1:3000/test instead with:
this command: set DEBUG=myapp:* & npm start it says: 404 not found
and with this command npm start it says request is not defined
what did i do wrong?
๐Ÿ‘จโ€๐Ÿซ You can change your test.js with this code below: ๐Ÿ‘‡
var express = require('express');
var router = express.Router();
var axios = require('axios');
/* GET home page. */
router.get('/', async function(req, res, next) {
try {
const response = await axios.get('https://mysite.ccc/api/test');
console.log(response.data);
res.json(response.data)
}catch(ex) {
console.log(ex)
res.status(400).send(ex.message);
}
});
module.exports = router;
I hope it's can help ๐Ÿ™.
Your test.js file should look like this
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// I don't see where you defined data, should be smth like: const data = {};
res.json(data);
});
module.exports = router;
Here you define your route, so when you start your app you are able to access the route http://127.0.0.1:3000/test.
You probably want to retrieve data from external website? For this you can use any http package, for example axios.
Your final test.js file will look like:
var express = require('express');
var router = express.Router();
var axios = require('axios');
/* GET home page. */
router.get('/', async function(req, res, next) {
const response = await axios.get('https://mysite.ccc/api/test');
res.json(response.data);
});
module.exports = router;
Note: I hope you somewhere call app.listen(3000) to start your web server.

How do I correctly import Express route modules?

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.

Simple configurable Express middleware not executing

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

Express: How can I handle this? (About `Route`)

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.

Resources