My express code:
var express = require('express');
var bodyParser= require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('default', {title: 'Home', users: ['a', 'b', 'c']});
});
app.post('/me', function(req, res){
res.send("2nd page");
var t1= req.body.username;
console.log(t1);
});
My template:
<form method="post" enctype="multipart/form-data" action="/me">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
I'm trying to print the form values in submitted page
I have not added any jQuery or anything in the head section
What's the mistake?
Problem is with your form enctype, I am using jade template system, just add "jade": "^1.6.0" in your package.json and do npm install
Server Code
var express = require('express');
var app = express();
var bodyParser= require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('test');
});
app.post('/me', function(req, res){
console.log(req.body.username);
res.send("done");
});
app.listen(8081);
console.log("Listening at 8081");
views/test.jade
doctype html
html
form(method="post",enctype="application/x-www-form-urlencoded" action="/me")
input(type="text",name="username")
input(type="password" name="password")
input(type="submit")
if you want multipart/form-data you need to use
var multer = require('multer'); app.use(multer())
Related
I am trying to output the value of title which i entered in the form in the /Add-Product link
Here is my app.js code
const http= require('http');
const path= require('path');
const express= require('express');
const app= express();
app.set('view engine', 'ejs');
app.set('views', 'Views');
app.use(express.static(path.join(__dirname, 'Public')));
app.get('/', (req, res, next)=>{
res.render('shop');
});
app.get('/admin', (req, res, next)=>{
res.render('admin');
});
app.get('/add-product', (req, res, next)=>{
res.render('addProduct');
});
app.post('/add-product', (req, res, next)=>{
console.log(req.body.title); //uable to display value of req.body.title
res.redirect('/');
});
app.listen(3000);
form part of the addProduct.ejs
<main>
<form action="/add-product" method="POST">
<p>Title</p>
<input type="text" name="title" id="title"/>
<p>Price</p>
<input type="text" name="price"/>
<p>Description</p>
<input type="text" name="description"/>
<button type="submit">Submit</button>
</form>
</main>
Unable to figure why the req.body.title is throwing an error as:Cannot read property 'title' of undefined
Please guide me on what i am missing.
By default, form submits the data to server in the content type of application/x-www-form-urlencoded. So you need to configure node js to receive this type of content. Use bodyParser to read the request body with json and encoded content.
Usage:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
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 have a very simple html form, and express server, but I can't make the routing work. I always get "Cannot Post" message. What did I miss?
var express = require('express');
var bodyparser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
app.use(express.bodyParser());
app.get("/", function(req, res){
res.sendFile(path.join(__dirname+"/index.html"));
});
app.post("/sendform", function(req, res){
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function(){
console.log("Server is running at port: 3000");
});
<form method="post" action="http://localhost:3000/sendform">
<input type="text" name="username" />
<input type="submit" value="küldés" />
</form>
With express 4.15.3, you have to use the body parser a bit differently.
I changed your code to this and I was able to post to it:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
//app.use(express.bodyParser());
app.use(bodyParser.json({
limit: "10mb"
}));
app.use(bodyParser.urlencoded({
limit: "10mb",
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("/sendform", function (req, res) {
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function () {
console.log("Server is running at port: 3000");
});
I'm doing a post request to '/' with a simple text input and expecting to see the data entered in req.body.course. When console logging req.body.course, I am getting an empty object back.
HTML
<html>
<head><title>New Course</title></head>
<body>
<form id="myform" action="/" method="post">
<input type="text" name="course" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
SERVER
var express = require('express');
var bodyParser = require('body-parser');
var app = express()
app.use(bodyParser.json())
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.post('/', function (req, res) {
var course = req.body.course;
res.send(course);
});
app.get('/', function (req, res) {
res.render('index');
});
app.listen(4000, function() {
console.log("Server is listening on port", 4000);
});
OUTPUT OF REQ.BODY
{}
Try
app.use(bodyParser.urlencoded())
you have to tell in headers what is the MIME type of your request
just add in request.
Content-Type='application/json'
Try to add the urlencoded middleware.
app.use(bodyParser.urlencoded())
or
app.use(bodyParser.urlencoded({
extended: true
}))
This parses URL encoded bodies since your request format is urlencoded.
You can refer to bodyparser urlencoded documentation.
I'm new to node , and I'm having so much trouble uploading a photo ;
here are my code :
var express = require("express"),
bodyParser = require('body-parser'),
app = express();
app.set('views', __dirname + '/Views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded());
app.post('/upload',function(request,response){
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
console.log(request.body);
response.end();
});
And here is the index.html Where I have my form :
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Test Drive Upload</h1>
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="thumbnail">
<input type="submit">
</form>
</body>
</html>
When ever I try to upload a photo and hit submit , I look at my console to see what is in the body ( I expect some hints to a file ! ) but here is the console after hitting the submit
{ username: '', password: '' }
There is No sign of any file or image
I've also tried this :
console.log(request.files);
console.log(request.form);
but both will throw undefiend in the console
Version 1 without using body parser:
var express = require('express');
var http = require('http');
var app = express();
app.use(express.static('./public'));
app.configure(function(){
app.use(express.methodOverride());
app.use(express.multipart({
uploadDir: './uploads',
keepExtensions: true
}));
});
app.use(app.router);
app.get('/upload', function(req, res){
// Render page with upload form
res.render('upload');
});
app.post('/upload', function(req, res){
// Returns json of uploaded file
res.json(req.files);
});
http.createServer(app).listen(3000, function() {
console.log('App started');
});
Version 2 with using body parser:
var express = require('express')
var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/uploads' }))
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
res.send('Uploaded: ' + req.files.image.name)
return next()
});
app.listen(3000);
console.log('Express app started on port 3000');
Here is a good Tutorial | Upload Image using Node.js
Happy Helping!
You have set multipart/form-data for uploading files, but none of the middleware you have enabled support that content-type. Normally you'd use a middleware like multiparty or busboy to parse multipart request data like your image.