Why is my NodeJS App not working as it should? - node.js

I don't understand what is my mistake but the app.Method are not really working.
server.js :
//express :
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
//middleware :
app.use(express.json);
app.use(bodyParser.urlencoded({ extended:false }))
//templating engine :
var ejs = require('ejs');
app.set('view engine', ejs);
//public directory :
app.use(express.static(__dirname + '/public'));
//pages:
app.get('/', function (req, res) {
console.log("Hello")
res.render('pages/index')
})
app.get('/post/new', function (req, res) {
res.render('pages/post-new')
})
app.post('post/new', function (err, req) {
console.log(req.body)
})
//listening
app.listen(8080, function (err, res) {
if (err) throw err;
else console.log(`Listening on 8080`)
});
I have my directory something like this:
node-modules
public
views
--pages
----index.ejs
----post-new.ejs
--partials
package-lock.json
package.json
server.js
I don't really understand why is it not working. I have tried adding console.log(req) in app.gets but they don't really log anything. And sorry for the dumb question.
EDIT: Answer is It is app.use(express.json()) NOT app.use(express.json)

Related

Express nodejs POST method return empty brackets

I can't get the value in my form. I am using a basic HTML form to send my data. When I try to test the return of the POST method in the console, I can't find the value of my input. This is my code:
let express = require('express');
let app = express();
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
my console always return {}
Add this to the front of your code:
app.use(express.urlencoded({ extended : true}));
app.use(express.json());
body-parser is no longer needed, as this feature is already provided in express.js.
also I would suggest you to do const express = require('express'); const app = express(); instead of let express = require('express'); let app = express();.
Do npm install 'body-parser
Then update your code like this
let express = require('express');
let app = express();
// For FORM input
var bodyParser = require('body-parser');
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
// Body parser For forms Actions
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
This should fix it

How can I prevent express-ejs-layouts for wrapping my other page?

I'm finding a page layout for node.js like laravel php have their Template for layout and it is perfect. I want to achieve it here in node.js and finally found this express-ejs-layouts but there is a problem in it that I cant see in their documentation the layout will wrap all of my pages specially my signin and signup page which have a different header and footer. How can we prevent express-ejs-layouts from wrapping my other page?
const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const server = require('http').createServer(app);
const expressLayouts = require('express-ejs-layouts');
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'project_101'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!');
});
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressLayouts);
app.get('/',(req, res) => {
let sql = "SELECT * FROM uploads";
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('index');
});
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/signin', (req, res) => {
res.render('signin');
});
app.get('/unknown-user', (req, res) => {
res.render('unknown-user');
});
app.get('/profile', (req, res) => {
res.render('profile');
});
const port = process.env.PORT || 3000;
// Server Listening
server.listen(port, function () {
console.log('Server successfully running at: -',port);
});
Finally got the solution for the problem express-ejs-layouts
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
You just need to declare your page as a layout and set it to false.
app.set("layout signin", false);
and render the page together with the layout.
app.get('/signin', (req, res) => {
res.render('signin', { layout: 'signin' });
});
ez fix ⚡️
You can bypass the template by sending the file back.
res.sendFile(path, options, fn);
options and fn are optional.

Nodejs shows Error "Cannot GET /test"

I am trying to retrieve output on other url / directory in nodejs but it's Display Error ("Cannot GET /test").
Please Suggest me what i have to do to get my output on ("http://localhost:8080/test").
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/test');
}
});
app.listen(8080);
OutPut : Cannot GET /test
You did not specify a route for /test. You should have
app.get('/test', function(req, res, next){
res.render('test'); // This should have a view
});
Here i writing sample. create views folder in root folder and add one test.pub file to views then just run
Note:dont forget to install pug and express
var express = require('express')
var app = express()
app.set('view engine', 'pug');
app.set('views','./views');
// here am directly sending response without using view engine
app.get('/', function (req, res) {
res.send('hello world')
})
// here am sending response with using view engine
app.get('/test', function(req, res){
res.render('test');
});
app.listen(8000,function(){
console.log(" Server is running on port 8000");
});

Multiple request url mapping handler in one controller does not work in Node Express JS

In my server.js file I have below url mappings:
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
In training.controller file I have mapped below way:
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
when call "/registerCourse","/getCourses","/getCourseDetails" throwing error saying:
"Cannot GET /getCourses"
Server.js -
require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
app.get('/', function (req, res) {
return res.redirect('/app');
});
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
training.controller.js-
var config = require('config.json');
var express = require('express');
var app = express();
var router = express.Router();
var trainingService = require('services/training.service');
app.use(router);
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
Solution:
Your route will be:
/registerCourse
/getCourses
/getCourseDetails
app.js
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/',require('./controllers/training.controller'));
/*
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
-- removed
*/
training.controller.js
var config = require('config.json');
var express = require('express');
// var app = express(); -- removed
var router = express.Router();
var trainingService = require('services/training.service');
// app.use(router); -- removed
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
In server.js you can use
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
and then try calling your
"/registerCourse","/getCourses","/getCourseDetails"

How to get post params in app.post

I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html.
in server.js file I have written below code
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var app = express();
var helpers = require('express-helpers')
helpers(app);
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// respond with "index.html" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/demo', function (req, res) {
res.render('demo.ejs');
});
app.post('/demo', function (req, res) {
console.log(res.body)
});
I want to know that in app.post how should id get post params
app.post('/demo', function (req, res) {
console.log(res.body)
});
I have tried console.log(req.body) but giving as undefined
Also tried console.log(res.body) but giving as undefined
Let me know how should I implement it?
you should use a middleware such as body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/demo', function (req, res) {
console.log(req.body)
});
Use the body-parser middleware. First, you need to install it using npm install body-parser. And then use it in your application like this
var bodyParser = require('body-parser');
.....
// For Content-Type application/json
app.use(bodyParser.json());
// For x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
....
app.post('/demo', function (req, res) {
console.log(req.body);
});

Resources