JQuery Ajax not working with ExpressJS

I am trying to send number over to the server with JQuery on the client side and received with NOde.JS and ExpresJS on the server side.

Here's the client code:

var value = $(object.selectId()).val();
    alert("Uploading " + value);
    $.ajax({
        type: 'POST',
        data: JSON.stringify({
            num : value
        }),
        contentType: 'application/json',
        url: '/testData',
        success: function (data) {
            alert('Successfully uploaded : ' + value + " and received " + JSON.parse(data).num);
        }
    }

Here's the server code:

app.post('/testData', function (req, res) {
var x1 = req.num
console.log("Got number : " + x1);
var x = JSON.stringify({
    num: (x1)
});
res.send(x);});

The server receives "undefined" and so does the client receive back.

Problem courtesy of: EternallyCurious

Solution

Can you try logging req.body on the server side( console.log(req.body); ? The variable num will be available as req.body.num instead of req.num .

Solution courtesy of: vmx

Discussion

Instead of express.bodyParser() or express.multipart() middlewares, you should use formidable or any other module to parse incoming form.

I'm sharing some code snippet to get ajax based file upload working, using formidable on the server side. We will also need jQuery Form Plugin .

Create a sample html form;

<form id="fileUploadForm" accept-charset="utf-8" method="post", action="/upload" enctype="multipart/form-data">
  <input type="file" name="userfile" multiple="multiple" />
  <button type="submit"> Upload </button>
</form>

Add some client side javascript to handle ajax uplaods. Assuming you've jQuery and jQuery form js loaded.

var $form = $("#fileUploadForm");
$form.submit(function (e) {
  // perform client side validations if any

  $(this).ajaxSubmit({
    error: function () {
      // handle error
    },

    success: function (response) {
      // handle success
    }
  });

  // Important: stop event propagation
  return false;
});

On serverside, add a file upload post route.

var upload = require('./upload');

app.post('/upload', upload.parse, upload.save, upload.respond, upload.errors);

Create upload.js to handle file uploads.

var fs = require('fs');
var util = require('util');
var path = require('path');
var formidable = require('formidable');

var upload = {

  parse: function parse(req, res, next) {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = process.env.TMP || process.env.TMPDIR || process.env.TEMP || '/tmp' || process.cwd();
    form.keepExtensions = true;
    form.type = 'multipart';

    form.parse(req, function (err, fields, files) {
      req.files = files;
      next(err);
    });
  },

  save: function save(req, res, next) {
    // validate if upload was successful
    if (!req.files || !req.files.userfile) return next(new Error('Upload data not received, can\'t proceed.'));

    var userfile = req.files.userfile;
    // examine this object for available attributes
    console.log(userfile);

    // ensure public/data dir exists
    var dataDir = 'public/data';
    var target = path.join(dataDir, userfile.name);

    fs.rename(userfile.path, target, function (err) {
      req.uploadLink = target.replace(/public/gi, '');
      next(err);

      // cleanup
      fs.unlink(userfile.path, function () {});
    });
  },

  respond: function respond(req, res, next) {
    var response = {
      result: 'success',
      upload: req.uploadLink,
      message: 'File uploaded!'
    };
    res.status(200).json(response);
  },

  errors: function errors(err, req, res, next) {
    console.log(err);
    var response = {
      status: 'failure',
      message: 'File upload failed!'
    };
    res.status(400).json(response);
  }
};

module.exports = upload;

Hope this helps, you can update the code to suit your needs. Let me know if need any clarification.

Good day!

Discussion courtesy of: vmx

This recipe can be found in it's original form on Stack Over Flow .

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章