1

On client i have:

var data = new FormData();

    data.append('users',  [{ name: "John"}] );
    data.append('excel', files[0]);
    console.log(data);
    $.ajax({
        url: 'url',
        type: 'POST',
        data: data,
        cache: false,
        processData: false,  
        contentType: false,

on server i next middleware:

app.use(bodyParser.json({limit:1024*1024}));
app.use(bodyParser.urlencoded());
app.use(multer());

But when i send somthing i have file and not parsed JSON body, it look like:

{ users: '[object Object]' }
siavolt
  • 6,869
  • 5
  • 24
  • 27

1 Answers1

0

I think you should show the controller code. But based on what you said in your comment.

And if i user JSON.stringify([{ name: "John"}]), i will be have this { users: '[{"name":"John"}]' }

Use:

JSON.stringify([{ name: "John"}])

Then on the receiving end:

{ users: JSON.parse('[{"name":"John"}]') }

Use JSON.parse on the received data.

So now you:

  • send data as string
  • recv data as string
  • JSON.parse recv'd string to convert it back to an object
majidarif
  • 18,694
  • 16
  • 88
  • 133
  • This cool, bro, but this work must do body-parser on middleware. Why he ignore JSON content? – siavolt Oct 15 '14 at 13:45
  • @user3776269 can you show the code for this `{ users: '[object Object]' }`? – majidarif Oct 15 '14 at 13:46
  • @majidarif: `data.append('users', [{ name: "John"}] );` – Felix Kling Oct 15 '14 at 13:48
  • @FelixKling no, I mean on the receiving end. The code for the controller. – majidarif Oct 15 '14 at 13:49
  • @user3776269: I don't think you can have the whole body being JSON if you want to send files as well. However, if you want that, you must not use form data but set the body directly with: `data: JSON.stringify(...)`. Also make sure to send the right content type headers. – Felix Kling Oct 15 '14 at 13:52
  • @majidarif router.post('/users', function(req, res){ console.log(req.body) }) and i give { users: '[object Object]' } – siavolt Oct 15 '14 at 13:58
  • @FelixKling On headers i have multipart/form-data content type. Also, if i use needle(module for node js) i send req, i have excellent result, parsed body and file. Code for req with needle: var data = { users: [{ name: "John"}], excel: { file: path.join(__dirname ,'fixtures/test.xlsx'), content_type: 'multipart/form-data' } }; needle.post(url, { multipart: true }, function(err, resp, body) {}) – siavolt Oct 15 '14 at 14:03
  • @user3776269: Assuming you are using https://github.com/expressjs/body-parser, did you read the README? *"This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: [...]"* I don't know `needle`, but I'm sure it won't encode the whole payload as JSON either. – Felix Kling Oct 15 '14 at 14:09