"Can't set headers after they are sent" and empty post request body


Jarques
26/4/2016 6:52 am
HOME ยป Web Development

I've been following a tutorial for a login/register authentication application. I keep getting the error "Can't set headers after they are sent" whenever I send POST requests. I tried to console.log the request body and it were empty. I don't know where I did wrong. Please help.

users.js

var express = require('express');
var router = express.Router();
var User = require('../models/User')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register', {title:'Register'});
});

router.get('/login', function(req, res, next) {
  res.render('login', {title: 'Login'})
});

router.post('/register', function(req, res, next) {
  var name = req.body.name;
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var password2 = req.body.password2;

  if (req.files && req.files.profileimage) {
    console.log('Uploading file...');

    var profileimageOriginalName =
req.files.profileimage.originalname;
    var profileimageName = req.files.profileimage.name;
    var profileimageMime = req.files.profileimage.mimetype;
    var profileimageExt = req.files.profileimage.extension;
    var profileimageSize = req.files.profileimage.size;
    var profileimagePath = req.files.profileimage.path;
  } else {
    var profileimageName = 'noimage.png'
  }

  req.checkBody('name', 'Name field is required').notEmpty();
  req.checkBody('email', 'Email field is required').notEmpty();
  req.checkBody('email', 'Email field is not valid').isEmail();
  req.checkBody('username', 'Username field is required').notEmpty();
  req.checkBody('password', 'Password field is required').notEmpty();
  req.checkBody('password2', 'Password does not
match').equals(req.body.password);
  var errors = req.validationErrors()

  if (errors) {
    res.render('register', {
      errors: errors,
      name: name,
      email: email,
      username: username,
      password: password,
      password2: password2
    });
  } else {
    var newUser = new User({
      name: name,
      email: email,
      username: username,
      password: password,
      profileimage: profileimageName
     })
  }

  User.createUser(newUser, function(err, user) {
    if (err) throw err;
    console.log(user);
  })

  req.flash('sucess', 'You are now registered and may login');
  res.location('/');
  res.redirect('/');
})
module.exports = router;

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 session = require('express-session');
var passport = require('passport');
var LocalStrategry = require('passport-local').strategy;
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var multer = require('multer')
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// handle file upload
var upload = multer({dest: './uploads'});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}))

app.use(passport.initialize());
app.use(passport.session());

app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));


app.use(flash())
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

app.use('/', routes);
app.use('/users', users);

// 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;

Related to : "Can't set headers after they are sent" and empty post request body
"Can't set headers after they are sent" and empty post request body
26/4/2016 6:52 am Web Development

I've been following a tutorial for a login/register authentication application. I keep getting the error "Can't set headers after they are sent" whenever I send POST requests. I tried to console.log the request body and it were empty. I don't know where I did wrong. Please help.

users.js

var express = require('express');
var router = express.Router();
var User = require('../models/User')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register', {title:'Register'});
});

router.get('/login', function(req, res, next) {
  res.render('login', {title: 'Login'})
});

router.post('/register', function(req, res, next) {
  var name = req.body.name;
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var password2 = req.body.password2;

  if (req.files && req.files.profileimage) {
    console.log('Uploading file...');

    var profileimageOriginalName =
req.files.profileimage.originalname;
    var profileimageName = req.files.profileimage.name;
    var profileimageMime = req.files.profileimage.mimetype;
    var profileimageExt = req.files.profileimage.extension;
    var profileimageSize = req.files.profileimage.size;
    var profileimagePath = req.files.profileimage.path;
  } else {
    var profileimageName = 'noimage.png'
  }

  req.checkBody('name', 'Name field is required').notEmpty();
  req.checkBody('email', 'Email field is required').notEmpty();
  req.checkBody('email', 'Email field is not valid').isEmail();
  req.checkBody('username', 'Username field is required').notEmpty();
  req.checkBody('password', 'Password field is required').notEmpty();
  req.checkBody('password2', 'Password does not
match').equals(req.body.password);
  var errors = req.validationErrors()

  if (errors) {
    res.render('register', {
      errors: errors,
      name: name,
      email: email,
      username: username,
      password: password,
      password2: password2
    });
  } else {
    var newUser = new User({
      name: name,
      email: email,
      username: username,
      password: password,
      profileimage: profileimageName
     })
  }

  User.createUser(newUser, function(err, user) {
    if (err) throw err;
    console.log(user);
  })

  req.flash('sucess', 'You are now registered and may login');
  res.location('/');
  res.redirect('/');
})
module.exports = router;

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 session = require('express-session');
var passport = require('passport');
var LocalStrategry = require('passport-local').strategy;
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var multer = require('multer')
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// handle file upload
var upload = multer({dest: './uploads'});

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}))

app.use(passport.initialize());
app.use(passport.session());

app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));


app.use(flash())
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

app.use('/', routes);
app.use('/users', users);

// 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;

request.body is empty when issuing POST requests containing JSON body
Web Development

I've struggling for few hours with this issue and I feel I'm stuck with it. I'm doing the tutorial of NodeJS, ExpressJS and MongoDB. I've built a simple API on ExpressJS.


When issuing a cURL POST request containing a JSON body the req.body is empty and therefore I see an error.


Hereby some source/details:


The cURL request:


curl -i http://localhost:3000/wines -X POST -H "Content-Type: application/json" -d "{'name': 'New Wine', 'year': '2009'}"

The route:


app.post('/wines', wines.addWine);

The API method:


Http POST request get headers and body
19/12/2014 7:10 pm Web Development

I am currently using the below mentioned code to make http post request and it only returns body But i want body and headers both SO how i can i get body and headers both with file_get_content method or CURL.

    $sURL = "url";
$sPD = "data";
$aHTTP = array(
  'http' => 
    array(
    'method'  => 'POST', 
    'header'  => "Content-Type: application/atom+xml"
    'content' => $sPD
  )
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;

req.body is empty when making a post request via http.request
Web Development

I have a nodejs app using bodyparser(), and this route :


app.post('/users', function(req, res){
res.json(req.body)
})

when i curl


curl -X POST 127.0.0.1:3000/users -d 'name=batman'

server sends back this json :


{ name: 'batman' }

my problem is when trying to make the same request with http.request, req.body is empty
i'm doing the same call though, here is a test.js file that i run with node :


var http = require('http');
var options = {
host: '127.0.0.1',
port: 3


HD Wallpapers
3D
3D Abstract
City
Celebrities
Indian Celebrities
Cars
Travel
Girls
Animals Birds
Movies
Sports
Black White
Nature
Planes
Anime
Food Drink
Dreamy Fantasy
Architecture
Games
Space
Holidays
Flowers
Love
Artistic
Baby
Beach
Bikes Motorcycles
Macro
Computers
Vector
Funny
Army
Textures
Brands
Misc
Music
Other
Privacy Policy - Copyrights Notice - Feedback - Report Violation - RSS 2017 © bighow.org All Rights Reserved .