JQuery Ajax not working with ExpressJS

前端 未结 2 1329
离开以前
离开以前 2020-12-22 06:36

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:

2条回答
  •  春和景丽
    2020-12-22 06:59

    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;

    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!

提交回复
热议问题