I made a register form using the bootstrap modal and I can't seem to make the POST request work.
This is the form in my en.pug file
#register.modal.fade(tabindex="-1" role="dialog" aria-labelledby="register form" aria-hidden="true")
.modal-dialog(role="document")
.modal-content
.modal-header
h5#exampleModalLabel.modal-title Sign Up
button.close(type="button" data-dismiss="modal" aria-label="Close")
span(aria-hidden="true") ×
.modal-body
form(action='/register' method='POST' )
.form-group
label.form-control-label(for="name") Name:
input#name.form-control(type="text", placeholder='first and last' name='name')
.form-group
label.form-control-label(for="email") Email:
input#email.form-control(type="email", placeholder='name#email.com', name='email')
.form-group
label.form-control-label(for="password") Password:
input#password.form-control(type="password" name='password')
.form-group
label.form-control-label(for="password") Confirm Password:
input#confirmed-password.form-control(type="password" name='confirmPassword')
hr.mb-4
// /registration form
.modal-footer
button.btn.btn-secondary(type="button" data-dismiss="modal") Close
button.btn.btn-primary(type="submit") Sign Up
This is my server.js file
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// serve static files from /public
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
// include routes
const routes = require('./routes/index');
app.use('/', routes);
app.listen(3000);
And this is the ./routes/index.js
var express = require('express');
const app = express();
var router = express.Router();
router.get('/', (req, res) => {
const cookie = req.cookies.language;
if (cookie) {
res.render('en', { cookie });
} else {
res.render('ro');
}
});
router.get('/en', function (req, res) {
res.cookie('language');
return res.render('en');
});
// GET /
router.get('/ro', function(req, res) {
res.clearCookie('language');
return res.render('ro');
});
app.post("/register", function (req, res) {
console.log('Hellooooooooooooooooo!')
});
module.exports = router;
When I fill out the form and press the Sign Up button I expect to show "Hellooooooooooooooooo!" in the console but nothing happens and I can't seem to figure out why. Am I missing something here?
EDIT: I figured out that I made a mistake in the pug indentation and the submit button was outside the form, reason for which completing the form and pressing the sign up button didn't do anything
You have to use bodyparser middleware.
We had to install body-parser before express version 4 update, but express now supports body-parser by default.
Just add
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Hope it helps.
In the HTML, in the input tags of the form of the bootstrap modal window, I used the name attribut (instead of the id attribute) and it is working.
//install body-parser npm and require it
const bodyParser = require('body-parser')
//write code below of app.use(cookieParser()) in server.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
router.post('/', function(req, res){
console.log(req.body) //here you will get POST data
})
Related
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
I am working on layouts and templating. I have a site where I have files "views/partials/header.ejs" and "views/partial/footer.ejs". I have the app.js file with templating set up as follows:
const express = require('express')
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const ejs = require('ejs');
const date = require(__dirname + '/date.js');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get('/', function(req, res) {
const year = date.getYear();
res.render('home', {copyrightYear: year})
});
app.listen(3000, function() {
console.log('Server started on port 3000');
});
What I need to do is pass the const copyrightYear into the partial "footer" instead of having to to input into each route. Any advice would be welcomed.
Thanks in advance.
you can't do that because when you make a request the server get the required file the does the logic on it and then it send it back to the browser .
so when you use this
app.get('/', function(req, res) {
const year = date.getYear();
res.render('home', {copyrightYear: year})
});
the server will get the home file which includes the partials files then pass the data then send it to the browser .
so you must make separate request for each file you want and then do the logic on it
I am trying to develop an application in NodeJs using express framework. My routing is working when I navigating from home to inner pages. But If I want to navigate from some inner page to homepage then it is not working.
Below is my app.js code.
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
//declare all routers
var home = require(path.join(__dirname, "/routes/index"));
var myaccount = require(path.join(__dirname, "/routes/myaccount"));
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', engines.handlebars);
var defaultViewPath = path.join(__dirname, "/views");
app.set('views', defaultViewPath);
app.set('view engine', 'html');
app.use('/', home);
app.use('/myaccount', myaccount);
Here if I have navigated from home to myaccount - Its working
But if I am navigating from myaacount to home - It reloads the same page.
Can anyone help me to resolve this issue.
To define routing using methods of the Express app object, use app.get() to handle GET requests
var express = require('express')
var app = express()
// When GET request is made to the homepage
app.get('/', function (req, res) {
res.render('home');
});
// When GET request is made to the myaccount
app.get('/myaccount', function (req, res) {
res.render('myaccount');
});
app.get('/myaccount/innerpage', function (req, res) {
res.send('Hello Inner Page');
});
//Page Not Found
app.use(function(req, res){
//render the html page
//res.render('404');
res.sendStatus(404);
});
Hope this could help you
use app.get and app.post Route Methods
app.get('/',function(req,res){
res.render('home');
});
app.get('/myaccount',function(req,res){
res.render('myaccount');
});
Or Create Router File For Home & myAccount
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Home Page')
})
module.exports = router
in Your app.js or index.js file , require route.js
var home = require('./route');
app.use('/', home)
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");
});
I don't know what I am doing wrong but extend doesn't working in my case.
server.js
var express = require('express');
var mongodb = require('mongodb');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var app = require('express')();
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'moj-sekret'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout:false});
app.get('/', function(req, res){
res.render('index', { authenticated: false});
console.log('index');
});
app.get('/login', function (req, res){
res.render('login');
console.log('login');
});
app.listen(3000);
example of jade
layout jade
doctype
html
head
title Przykład MongoDB
body
h1 Moja
hr
block content
login jade
extends layout
block content
form(action="/login", method="POST")
fieldset
legend Logowanie
p
label Adres e-mail
input(name="user[email]", type="text")
p
button Wyślij
p
a(href="/") Powrót
i use express 4.7.2 and jade 1.9.1 and i dont have any error or bugs when run node
First of all, your jade file seems to be wrong:
extends layout
block content
form(action="/login", method="POST")
fieldset
legend Logowanie
p
label Adres e-mail
input(name="user[email]", type="text")
p
button Wyślij
p
a(href="/") Powrót
There might be something else as well, but try this first.