0

I had my web app working wonderfully until I attempted to connect a photo upload to a form.

Now, it appears node doesn't receive any of the ajaxed form fields!.

HTML
==========

<form method="post" action="#" enctype="multipart/form-data">
        <input type="text" name="labelForPhoto" />
        <input type="file" name="imgUploader" />
        <input type="submit" value="savephoto">
</form>

OR

<form method="post" action="#" enctype="multipart/form-data">
        <input type="text" name="username" />
        <input type="password" name="password" />
        <input type="submit" value="login">
</form>


JS
================

var formData = new FormData(this);

$.ajax({
    type: "post",
    data: data, 
    url: "http://localhost:8080/savephoto", // or /login
    xhrFields: {withCredentials: true},
    contentType: false, 
    processData: false, 
    enctype: 'multipart/form-data',
    cache: false,
    success: function(data, textStatus, xhr)
    {
        console.log("success");
    },
    error: function()
    {
        console.log("error");
    }
 });


NODE
============

const express = require("express");
const app = express();
const cors = require('cors');
const port = 8080;
const session = require('express-session');
const router = express.Router();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});


app.use(express.urlencoded());


/* this calls the session function for every request to the end point */
app.use(session({
  secret: 'work hard',
  resave: true,
   saveUninitialized: false,
     cookie: {
    maxAge: 36000000,
    httpOnly: false // <- set httpOnly to false
  }
}))

router.get("/savephoto", function(req, res){
    Users.all(function(err, results){
        console.log(req.body.labelForPhoto); ////// THIS IS ALWAYS UNDEFINED NOW
    });
});

router.get("/login", function(req, res){
    Users.all(function(err, results){
        console.log(req.body.username); ////// THIS IS ALWAYS UNDEFINED NOW
    });
});

When I put the form back to have no multi-part and I get rid of the FormData object in the JavaScript IE, remove the fileupload needed stuff for the AJAX call, then it sends the form fields again as expected.

I was trying to add the multi-part form stuff so I could send an image to the server with a title and other details via ajax.

Nathan Leggatt
  • 398
  • 1
  • 6
  • 18

1 Answers1

0

Once you start using AJAX, you get your data a slightly different way. See this answer.

Nathan Hawks
  • 557
  • 4
  • 14