i've been trying to get the data in a form with the POST method, but i don't get any, i've been reading a book to learn about expressjs.. this is my form:
<form method="post">
<div class="form-group">
<label for="usernameInput" class="col-md-2">Username</label>
<div class="col-md-12">
<input type="text" class="form-control" id="usernameInput" name="username" placeholder="Enter username">
</div>
</div>
<div class="form-group">
<label for="passwordInput" class="col-md-2">Password</label>
<div class="col-md-12">
<input type="password" class="form-control" id="passwordInput" name="password" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Log in</button>
</form>
and this is my node code.
/*
Chat application for #node.js
express version.
*/
//Load modules.
var express = require('express'),
http = require('http'),
socket = require('socket.io'),
swig = require('swig'),
fs = require('fs');
//Load config.
console.log('Loading configuration.');
var config = fs.readFileSync('config.json');
var config = JSON.parse(config);
var port = config.port;
var views = config.views;
console.log('Configuration loaded.');
//Initiate express module in app.
var app = express();
//Global vars
var Title = "Node.js Chat";
var result = '';
app.engine('html', swig.renderFile);
//Set view engine.
app.set('view engine', 'html');
//Set the directory for views.
app.set('views', __dirname + '/views');
swig.setDefaults(
{
cache: false
});
app.get('/', function(request, response)
{
console.log('GET OK');
response.render('index',
{
'Title': Title,
'result': result,
});
});
app.post('/', function(request, response)
{
console.log('POST OK');
console.log(request.body);
response.render('index',
{
'Title': Title,
'result': 'Post detected.',
});
});
//logger.
app.use(function(request, response, next)
{
console.log('%s %s', request.method, request.url);
var file = request.url.slice(1 + request.url.indexOf('/'));
app.get(request.url, function(request, response)
{
response.render(file,
{
//Var to be named in the render : value;
'Title': Title,
'result': result,
});
});
next();
});
//Set directory for static files (css, js, img)
app.use(express.static(__dirname + '/public'));
//Run the app.
http.createServer(app).listen(port, function()
{
console.log('Server listening to ' + port);
});
i get "undefined" in request.body, which i dont know why i get this error, i've tried with other methods like request.param, or request.query, but they get nothing, i've made sure the post is detected and its why it sends the message that's being detected, but i want to get the data in the form..
You need the now-separate body-parser middleware. Run npm install body-parser or add body-parser to your package.json and npm install it.
Add var bodyParser = require('body-parser'); to your module-loading, then after instantiating your app, add the middleware with app.use(bodyParser());. That will populate req.body for the form.
add in app.js:
app.use(express.bodyParser());
As the comment indicated, it depends on the express version.
It works with 3.x as stated above.
For 4.0, you must manually include these frameworks that were previously included. See the note from vision media (overview tab):
https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x
These are NOT included to allow independent updates
Related
My project was working fine till last week and now all of a sudden my post requests are not working . i tried all methods and read other questions of stack overflow but was unable to fix the issue . can some one please help me?
Issue : req.body is undefined and also whenever i try upload a file "cannot read property path of undefined" is the error.
i'm using express middle ware to parse the request body . i also have my form enctype to multipart/form-data..
Code snippet is below :
require('dotenv').config()
const express = require('express');
const app = express();
const router = express.Router();
const session = require('express-session');
const fs = require(`fs`);
const mysql = require(`mysql-await`);
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const multer = require('multer');
const {storage} = require('../cloudinary');
const upload = multer({storage});
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Sujanya#1978",
database: "dept"
});
con.connect((err) => {
if (!err) {
console.log("Connected");
}
else {
console.log(err)
}
})
router.get('/naaccircular',(req,res)=>{
(async () => {
let results = await con.awaitQuery('select* from dept.naaccircular;');
res.render('Naac_circular',{Egs : results})
})();
})
router.get('/naaccriteria',(req,res)=>{
(async () => {
flet results = await con.awaitQuery('select* from dept.naaccriteria;');
res.render('Naac_criteria_files',{Fgs : results})
})();
})
router.post('/naacaddcircular',upload.single('circularfile'),(req,res) => {
console.log(req.body);
const n = req.body.circularname;
const d = req.body.circulardate;
const l = req.file.path;
con.connect(function(err){
var records = [n,d,l];
con.query("insert into dept.naaccircular (cirname,cirlink,cirdate)
VALUES (?,?,?)", [n,l,d] , function (err, result, fields){
if (err) throw err;
})
});
console.log(n);
console.log(l);
console.log(d);
res.redirect('/naaccircular');
})
module.exports = router;
style="margin-top:80px; background-color: white;">
<form action="/naacaddcircular" method="POST" class="row g-3 form-container" enctype="multipart/form-data">
<h3 style="text-align: center;">Naac Circular</h3>
<div class="mb-3">
<label for="ii" class="form-label">Name</label>
<input id="ii" name="circularname" class="form-control" type="text" placeholder="Default input"
aria-label="default input example">
</div>
<div class="mb-3">
<label for="jj" class="form-label">Date</label>
<input id="jj" name="circulardate" class="form-control" type="date">
</div>
<div class="input-group mb-2">
<input type="file" class="form-control" name="circularfile"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"
aria-label="Upload">
<!--<button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Button</button>-->
</div>
<button type="submit"
class="btn btn-primary position-relative start-50 botttom-0 translate-middle-x">Upload</button>
</form>
</div> ```
The problem is with cloudinary module. I have rectified it, there are no errors in the post method.
Once upload.single() function is removed from the router.post() function I'm able to get the req.body(),
So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())
In app.post("/compose"), I am trying to redirect the URL to the home page, but it's not redirecting to the homepage.
What mistake am I making?
Kindly help, redirecting to the homepage res.redirect("/") not working.
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const homeStartingContent = "HOME CONTENT ........";
const aboutContent = "ABOUT CONTENT .......";
const contactContent = "CONTACT CONTENT ......";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
var posts = [];
app.get("/", function(req, res){
res.render("home", {homeContent: homeStartingContent});
console.log(posts);
});
app.get("/about", function(req, res){
res.render("about", {aboutContent: aboutContent});
});
app.get("/contact", function(req, res){
res.render("contact", {contactContent: contactContent});
});
app.get("/compose", function(req, res){
res.render("compose");
});
app.post("/compose", function(req, res){
const post = {
title: req.body.postTitle,
content: req.body.postBody
};
posts.push(post);
res.redirect("/");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
I was able to redirect when I ran your code in local by changing this:-
res.render("home", {homeContent: homeStartingContent});
to
res.send("I am in get method");
This means your code is working fine. The problem could be with your "home" page.
Could be an issue rendering it.
With your code, I was getting the following error:-
Failed to lookup view "home"
This was because there was no file named "home".
Is your code working fine in your system? If there is an error, please enter that in your question.
Actually it was a typing mistake from my side. Instead of passing action="/compose" method="post" into the form element, i mistakenly passed into the div element(like that div class="form-group" action="/compose" method="post").
<%- include('partials/header'); -%>
<h1>COMPOSE</h1>
<form class="form-group" action="/compose" method="post">
<div>
<label>Title</label>
<input type="text" class="form-control" name="postTitle">
</div>
<div class="form-group">
<label>Post</label>
<textarea class="form-control" rows="3" cols="25" name="postBody"></textarea>
</div>
<button class="btn btn-primary" type="submit" name="button">Publish</button>
</form>
<%- include('partials/footer'); -%>
I'm starting in NodeJS and to practice I'm creating a project where I have a form with some fields, the form is created inside the views folder as teste.ejs.
Teste.ejs
<div class="container">
<form id="form1" method="POST" action="/inndetails.js">
<div class="row">
<div class="col-25">
<label for="fname">MerchantID</label>
</div>
<div class="col-75">
<input type="text" id="fname" name="merchantid" placeholder="MerchantID..">
</div>
<div class="row"><div class="row">
<div class="col-25">
<label for="fname">Valor</label>
</div>
<div class="col-75">
<input type="text" id="valor" name="valor" placeholder="Valor..">
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
This form has two fields "MerchantID" and "Valor". I want when I submit using POST the values from these fields go to an JS file called "inndetails.js" and execute this file.
Inndetails.js
sdk.getIinDetails({
'psp_Version': '2.2',
'psp_MerchantId': '**From the form**',
'psp_IIN': '**From the form**',
'psp_PosDateTime': '2016-12-01 12:00:00'
},
function (error, response) {
if (error) {
console.log(error)
} else {
console.log(response);
}
});
I am already using Express and Body Parser, In my routes folder I have the file index.js contains:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
router.post('/teste2', urlencodeParser, function(req, res) {
console.log(req.body);
res.render('teste2', ´{data: req.body});
});
I can get the values from the form and show in another page for example in teste2.ejs, using:
<p>MerchantID: <%= data.merchantid %></p>
<p>Valor: <% data.valor %></p>
I think you need to change your index.js file to
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
router.post('/teste2', bodyParser.urlencoded({limit: '50mb', extended: false }), function(req, res) {
console.log(req.body);
res.render('teste2', ´{data: req.body});
});
The parameters {limit: '50mb', extended: false } is an option, and you can see the others here https://www.npmjs.com/package/body-parser
`
I'm having some problems trying to send an email from my contact form. I'm using the module NodeMailer.
I'm using node.js and I don't really understand how it works... but anyway, I have this form:
<form role="form" method="post" action="/" class="contact-form">
<input type="hidden" name="scrollPosition">
<input type="hidden" name="submitted" id="submitted" value="true">
<div class="col-lg-4 col-sm-4" data-scrollreveal="enter left after 0s over 1s" data-sr-init="true" data-sr-complete="true">
<input required="required" type="text" name="name" placeholder="Your Name" class="form-control input-box" value="">
</div>
<div class="col-lg-4 col-sm-4" data-scrollreveal="enter left after 0s over 1s" data-sr-init="true" data-sr-complete="true">
<input required="required" type="email" name="email" placeholder="Your Email" class="form-control input-box" value="">
</div>
<div class="col-lg-4 col-sm-4" data-scrollreveal="enter left after 0s over 1s" data-sr-init="true" data-sr-complete="true">
<input required="required" type="text" name="subject" placeholder="Subject" class="form-control input-box" value="">
</div>
<div class="col-lg-12 col-sm-12" data-scrollreveal="enter right after 0s over 1s" data-sr-init="true" data-sr-complete="true">
<textarea name="message" rows="12" class="form-control textarea-box" placeholder="Your Message"></textarea>
</div>
<button class="btn btn-primary custom-button red-btn" type="submit" data-scrollreveal="enter left after 0s over 1s" data-sr-init="true" data-sr-complete="true">Send Message</button>
</form>
and here's my code in index.js :
app.post('/', function(req, res){
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "me#gmail.ca",
pass: "application-specific-password"
}
});
//Mail options
mailOpts = {
from: req.body.name + ' <' + req.body.email + '>', //grab form data from the request body object
to: 'me#gmail.ca',
subject: req.body.subject,
text: req.body.message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
console.log("Failed");
}
//Yay!! Email sent
else {
console.log("Succes");
}
});
});
But when I try and press the button "Send Message", it just open the page Not Found 404. I don't understand why. I never used node.js before, I'm using it because the guy I'm working with wanted to use it... So I really have no clue.
There's also "app.js", shall I write this code there instead? I'm kinda lost, we're trying to merge 3 wordpress themes in one and we need to convert everything (because wordpress is php...) and I've been trying to implement the contact form for 2 weeks... and it seems like nothing wants to work.
Anyone has an idea? Thanks a lot.
Here I added the 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 nodemailer = require('nodemailer');
//var knob = require('jQuery-Knob');
var index = require('./routes/index');
var prices = require('./routes/prices');
var projects_startup = require('./routes/projects_startup');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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(knob);
app.use('/', index);
app.use('/prices', prices);
app.use('/projects_startup', projects_startup);
// 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;
Thanks again.
OK, I see your app.js file, everything looks good there, the problem could be when you are posting your form, the browser is expecting a POST page at '/', so you should render a success page, or you can just redirect to the original GET page. You should be able to add a line to your success page.
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
console.log("Failed");
}
//Yay!! Email sent
else {
console.log("Succes");
res.render('successPage')
//or you can do res.redirect('/')
}
});