kentor
kentor

Reputation: 18524

Express.js access fields of serialized Form Data

I am struggling with accessing specific fields of my serialized formdata in my express router.

This is my ajax request:

var formData = $("#add-fut-account-form").find("select, textarea, input").serialize();
$.ajax({
  url: "/accounts/insert",
  type: "POST",
  data: {formData},
  success: function (response) {
    $("#addFutAccountResponse").append(response);
  },
  error: function (xhr) {
    alert("Error while trying to insert a new account!");
  }
})

This is my router:

router.post('/insert', function(req, res)
{
    var formData = req.body.formData;
    console.log(formData);
});

My console.log() output:

email=kentor%40gmail.com&password=dsadsa&secret=123&platform=P&account-type=x&proxy=&rpm=8&threshold=3.5&optional-comment=&is-active=on

My problem:

How should I serialize / send / receive my formData so that I can easily access specific fields (such as email, password) from my form. I tried using req.body.formData.email which doesn't work (result: undefined). I know two possible ways how to solve this issue, but they appear to be a roundabout way. Thus I want to know what the best practice for handling formdata with express is.

Edit: I am already using the bodyParse in my app.js:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

Upvotes: 0

Views: 1391

Answers (1)

Dima Grossman
Dima Grossman

Reputation: 2830

try making the ajax as follows:

var formData = $("#add-fut-account-form").find("select, textarea, input").serialize();

$.ajax({
  url: "/accounts/insert",
  type: "POST",
  data: formData,
  success: function (response) {
    $("#addFutAccountResponse").append(response);
  },
  error: function (xhr) {
    alert("Error while trying to insert a new account!");
  }
})

remove the curly braces on data

Upvotes: 1

Related Questions