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();
});
Related
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.
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())
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.
I really apologize if I'm leaving something out and am totally stupid, but I've checked and checked over again a number of times, and the file upload functionality is just not working over here. I made a super minimal app to demonstate. Just generated a new express app with the most up-to-date version (3.4.7) and added the least i could to make a file upload work.
Here's my app.js file
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/tasks', function(req, res) {
res.render('form');
});
app.post('/tasks', function(req, res) {
console.log(req.files);
res.send('ok');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
exports = module.exports = app;
And here's my form.jade view file:
doctype html
html
head
title Task Upload
body
form(action='/tasks', method='post', enctype='multipart/form-data')
input(name='task', type='file')
input(type='submit')
Everytime I try to upload a file, req.files logs out undefined. Can anyone save me out from this problem?
Add the following in your app.js
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files'}));
});
And then try to access as follows;
req.files.task
It is recommended not to use bodyParser, but to simply define the type of handling you want. In your case since its file uploading, you can enable it as follows
app.configure(function(){
app.use(express.methodOverride());
app.use(express.multipart());
});
You can read about why using bodyParser() is not a good idea in the following link.
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
In Express 4, req.files is no longer available on the req object by default.
To access uploaded files on the req.files object, use multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty,.
I want to post some data to server. The problem is that, it seems the server cannot receive the data.
So my post data is like this:
name=hello&email=there&message=sometext
and my server code is like this:
var url = require('url'),
express = require('express'),
http=require('http'),
path = require('path'),
nodemailer = require('nodemailer');
var app = express();
var server = http.createServer(app);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('home');
});
app.use(express.bodyParser());
app.post('/', function(req, response){
console.log(req.body);
// console.log(request.body.name);
});
server.listen(4000);
console.log('server running ' + 'now ' + Date.now());
when the console.log(reg.body) run, the terminal output is "undefined"
All query strings output are parsed by default by app.use(express.bodyParser());.. simple solution to your problem is try logging req.query , something like
console.log(req.query);
move app.use(express.bodyParser())); ahead of app.use(express.static(path.join(__dirname, 'public')));