NodeJS upload photo - node.js

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.

Related

why unable to display value of title?

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 }));

Cannot post to a server in express

I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.

req.body returns empty object when posting using form data in nodejs express

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.

Unable to post form details using Express js

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())

express.bodyParser not parsing?

I've stripped everything down to the absolute bare bones to try and fine out whats wrong, and still can't get bodyParser to do anything. It won't even work for .txt files.
server.js
var cfg = require(__dirname + '/config'),
express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.logger(cfg.LOGGER));
app.use(require('connect').bodyParser());
app.use(express.static(__dirname + '/public'));
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.get('/', function(req, res) {
res.render('index');
res.end();
});
app.post('/upload', function(req,res) {
console.log(req.body.file);
res.end();
});
app.listen(2017);
index.ejs
<form enctype="multipart/form-data" action="/upload" method="POST">
<input id="multipart/form-data" type="file" name="foo" />
<button>Upload</button>
</form>
the result is that req.body.file is undefined
You can access the file using req.files.<yourFileInputFieldName>:
console.log(req.files.foo);
More info in this section of the docs.
Change this
app.use(require('connect').bodyParser());
as
app.use(express.bodyParser());
app.post('/upload', function(req,res) {
console.log(req.body.foo);//in req.body u have to mention the name of the file..
res.end();
});

Resources