I have written a html form and trying to retrieve the values in node js server.
<form action="/newPost" method="post">
First Name: <br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
var express = require('express');
var bodyParser = require('body-parser');
const hbs = require('hbs');
var {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var app = express();
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
app.use(bodyParser.json());
const port = process.env.PORT || 3000;
app.post('/newPost', (req, res) =>{
console.log(req.body.text);
console.log(req.params.firstname);
console.log(req.body.firstname);
res.send(req.body.firstname);
});
expecting mickey but shows undefined
Related
How do I post a value which is on the client-side and get it on the server-side.
example:
<form action="/myform" method="POST">
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.get('/myform', function(req, res){
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
app.listen(3000)
<form action="http://127.0.0.1:3000/myform" method="post">
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myform', function(req, res) {
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
Your code seems to be fine, apart from wrong method name. In HTML form you have mentioned POST method but at server you are listening to GET method. So just change, app.get('/myform', to app.post('/myform',.
It should work.
Im using express, node, bodyParser to pull information from a contact form and post it to the terminal. When I run the code and access my demo site through LocalHost:3000, upon submitting, my input items are not showing up in the terminal.
I've tried changing the form attributes action="send" action="/send" action="/"
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
/ Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
//Form HTML code
<form action="send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
Have you tried console logging the req instead of the res for the app.post?
If you are doing console.log(req.body) then this should output a long json object. If this is not happening, then you are not hitting the url.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const nodemailer = require('nodemailer');
const app = express();
// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('contact', { layout: false });
});
app.post('/send', (req, res) => {
console.log(res.body);
});
The problem is in your html code. I have made some changes, Try this.
//Form HTML code
<form action="http://localhost:9000/send" method="POST">
<input name="name" type="text" id="name" placeholder="NAME: First & Last">
<input name="email" type="text" id="email" placeholder="EMAIL:">
<textarea name="text" id="text" cols="30" rows="10" placeholder="QUESTION OR INQUIRY:"></textarea>
<br>
<button type="submit">Submit</button>
</form>
I am using:
var express = require("express"),
app = express(),
bodyParser = require("body-parser");
with:
app.use(bodyParser.urlencoded({extended: true}));
Form:
<form action="/[route]" method="GET">
<input type="text" name="[name]">
<input type="submit" value="Show Results">
</form>
Route:
app.get("/[route]", function(req, res){
console.log(req.body.[name]);
});
The issue I am having is when I try to access the req.body.[name of input] it is 'undefined'
It's like the body parser is not working and I am not sure why.
I am using multer module to upload files to my application with a multiform-data enctype on my form. However, I have tried all possible solutions I have found to upload the file in vain. I am receiving always a "Cannot read property path of undefined or file of undefined. Here below is my view, controller and config files, anyone can help point was it wrong?
View
<form method="post" action="/images" enctype="multipart/form-data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label for="file" class="col-sm-2 control-label">Browse:</label>
<div class="col-md-10">
<input type="file" name="file" id="file" class="form-control">
</div>
</div>
controller:
var tempPath = req.files.path;
var ext = path.extname(req.files.name).toLowerCase();
var finalPath = path.resolve('./public/upload' + imageUrl + ext);
config file:
var path = require('path');
var express = require('express');
var routes = require('./routes'); //routes for GET, POST...requests
var exphbs = require('express-handlebars'); //templating engine
//var bodyParser = require('body-parser'); //form submission request are accessible with req.body
var cookieParser = require('cookie-parser'); //cookies to be send and received
var morgan = require('morgan'); //module for logging - used in debugging
var methodOverride = require('method-override'); //for older browser to fake REST verbs
var errorHandler = require('errorhandler'); //handles error through the middleware
var moment = require('moment'); //npm module to handle dates formating
var multer = require('multer'); //to handle file uploading
module.exports = function(app) {
app.use(morgan('dev'));
//app.use(multer({dest: path.join(__dirname, 'public/upload/temp')})); //proper use of multer
app.use(multer({ dest: path.join(__dirname,'public/upload/temp')}).any());
app.use(methodOverride());
app.use(cookieParser('IciCestParis'));
routes(app); //moving the routes to route folder
app.use('/public/', express.static(path.join(__dirname,'../public')));
Problem Statement: When I am running node.js I am getting an error
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/
Expected Result: The page should display and the user can insert data to the DB.
Here is my Code:
filter.js
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(express.bodyParser());
filter.use(express.methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_emailid: String,
name: String,
age: Number
});
var user = mongoose.model('emp', Schema);
filter.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
})
});
filter.post('/new', function(res, req){
new user({
_emailid:req.body.email,
name:req.body.name,
age:req.body.age,
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port' + app.get('port'));
});
Here is my HTML code:
<html>
<head>
<title>Please enter your details</title>
</head>
<body>
<h3>Please enter your details</h3>
<p>Please register below!!!</p>
<form action="/new" method="POST">
<label for="email">Email: </label>
<input type="email" name="email" /><br>
<label for="name">Name: </label>
<input type="text" name="name" /><br>
<label for="age">Age: </label>
<input type="number" name="age" /><t>
<input type="number" name="age" /><br>
<input type="submit" />
</form>
</body>
</html>
There are a number of changes with express 4.x. Like the error says, all of the middleware has been removed.
Update your package.json to include the "new" packages, a basic list can be found here and a full list, https://github.com/expressjs
Basically you need to edit
filter.use(express.bodyParser());
And replace it by,
filter.use(bodyParser());
You will have to do it for the methodOverride middleware as well.
Make sure you have all modules insatlled.
Hope this helps you,
var express = require('express'),
http = require('http'),
fs = require('fs'),
bodyParser = require('body-parser'),
methodOverride=require('method-override'),
io = require('socket.io'),
filter = express();
mongoose = require('mongoose');
//all environments
filter.set('port', process.env.PORT || 3000);
filter.set('views', __dirname + '/views');
filter.set('view engine', 'jade');
filter.use(bodyParser());
filter.use(methodOverride());
//filter.use(filter.router);
filter.use(express.static(path.join(__dirname,'public')));