JQuery Ajax不能与ExpressJS一起使用

时间:2013-12-04 06:22:38

标签: jquery node.js express

我正在尝试使用JQuery在客户端向服务器发送数字,并在服务器端收到NOde.JS和ExpresJS。

这是客户端代码:

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);
        }
    }

这是服务器代码:

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

服务器收到“未定义”,客户端也会收到回复。

2 个答案:

答案 0 :(得分:2)

您是否可以尝试在服务器端req.body上记录console.log(req.body);?变量num将以req.body.num而不是req.num的形式提供。

答案 1 :(得分:1)

而不是express.bodyParser()express.multipart()中间件,您应该使用formidableany other module来解析传入的表单。

我正在共享一些代码段,以便在服务器端使用formidable来启用基于ajax的文件上传工作。我们还需要jQuery Form Plugin

创建示例html表单;

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

添加一些客户端javascript来处理ajax uplaods。假设你已经加载了jQuery和jQuery表单js。

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;
});

在服务器端,添加路径后文件上传。

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

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

创建upload.js来处理文件上传。

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;

希望这有帮助,您可以更新代码以满足您的需求。如果需要任何澄清,请告诉我。

美好的一天!