John Smith
John Smith

Reputation: 578

POST parameters in ExpressJS

I am working on a simple texteditor that saves and loads text files through an Node/ExpressJS server. Loading is fine, but saving doesn't work yet due to me not being able to transmit the data to the server-app correctly.

enter image description here

I send the data via XMLHttpRequest to the server in a POST request, which works fine according to the network-profiler in dev-tools, the 'handler_save' function is called, but no parameters are received.

What am I doing wrong? (here is a snippet of the server code, altered for demonstration:)

express = require('express')();

function init_save_load(){
  var bodyParser = require('body-parser');
  express.use(bodyParser.urlencoded({ extended: true }));
  express.use('/save', handler_save );
  express.use('/load', handler_load );
}

...

function handler_save(req, res){
  console.log(req.body);    // "{name:post.txt,data:testing}"
}

Upvotes: 0

Views: 136

Answers (2)

A.B
A.B

Reputation: 20445

make sure you are parsing the request body so it can work

var bodyParser = require('body-parser');
app.use(bodyParser());

bodyParser is a part of "Connect", a set of middlewares for node.js. Here's the real docs and source from Connect: http://www.senchalabs.org/connect/bodyParser.html

finally console log the req.body and see what is in there

 console.log(req.body)

Upvotes: 2

mscdex
mscdex

Reputation: 106698

Not only do you need to use a body parsing middleware as Abdul mentioned, but your request needs to have the correct Content-Type. Currently you are sending Content-Type: text/plain, but it should be Content-Type: application/x-www-form-urlencoded for simple forms or Content-Type: multipart/form-data for forms containing files.

Upvotes: 1

Related Questions