Git Product home page Git Product logo

Comments (17)

alexindigo avatar alexindigo commented on July 19, 2024 141

Hey,

The thing is you can send only strings over the wire, so complex data types, like object should be encoded somehow and since there are many way to encode objects, FormData leaves it to developer to choose proper encoding mechanism that supported on the other end. For example it could be a JSON string or a form-urlencoded string.

Something like:

var details = JSON.stringify({age: 12});
form.append('details', details);

Let me know if you have more questions.

from form-data.

alexsmartens avatar alexsmartens commented on July 19, 2024 25

I was trying to post a complex data structure without pickling it into json to set up a simple data flow from React to Rails, and this thread was the most helpful piece of information. Just in case someone is looking for an example:

data to be posted:

{
  library: "favorite",
  movie: {
    name: "James Bond Skyfall",
    year: "2012",
    screenshots: [file1, file2],
  },
}

implementation with FormData:

const formData = new FormData()

formData.append("library", "favorite")
formData.append("movie[name]", "James Bond Skyfall")
formData.append("movie[year]", "2012")

formData.append("movie[screenshots][]", file1)
formData.append("movie[screenshots][]", file2)

from form-data.

alexindigo avatar alexindigo commented on July 19, 2024 4

You'd need to handle decoding one way or another and because implementations differ from server to server, you need to find combination that would work for your setup.

One of the ways is to stay away from nested structure, something like:

var form = new FormData();
form.append('name', 'Name');
form.append('age', '12');

or

var form = new FormData();
form.append('name', 'Name');
form.append('details_age', '12');

or PHP-style (not sure if Hapi would support it out of the box):

var form = new FormData();
form.append('name', 'Name');
form.append('details[age]', '12');

Another solution will be to encode all your data as JSON and send it to the server with proper headers,
there should be examples in Hapi documentation.

from form-data.

alexindigo avatar alexindigo commented on July 19, 2024 4

it maybe common case for some apps, but some other apps work with url-encoded data, and even with url-encoding there are multiply ways, like standard HTTP way and PHP array-friendly way.

And if all you need is JSON.stringify, there should be no problem in doing it in "user"-land (i.e. form.append('data', JSON.stringify(myData)), right?

Throwing errors in general meant for developer errors, to notify developer of the unacceptable behavior. And for developers it's much easier to find out about the problem this way, then somewhere deeper in stack because some library took freedom to assume things for the developer, especially for dynamic languages like JS, where you can accidentally pass object instead of a string.

from form-data.

petermilan avatar petermilan commented on July 19, 2024

Hello,
thanks for the response. My use case is that I am using this module just in my tests to simulate the form post to the hapijs server.

I've already tried JSON.stringify but unfortunately, the field was arriving as a string instead of an object. I don't want to add into my production code logic to parse some of the fields from string to json just because of tests:(

from form-data.

petermilan avatar petermilan commented on July 19, 2024

Thanks php style helped for hapi, I thought that I' ve already tried this, but obviously I had some bug there before :)

from form-data.

NodeGuy avatar NodeGuy commented on July 19, 2024

How about if append receives an object then it assumes it should be encoded with JSON.stringify and it sets Content-Type to application/json? This seems like a common use case to me.

It wouldn't be worse than the current behavior of TypeError: Object #<Object> has no method 'on'.

from form-data.

NodeGuy avatar NodeGuy commented on July 19, 2024

Excellent points, I agree.

from form-data.

mifi avatar mifi commented on July 19, 2024

Is there any npm module for transforming an object to PHP style array? recursively

from form-data.

mifi avatar mifi commented on July 19, 2024

Found one: https://github.com/therealparmesh/object-to-formdata/

from form-data.

amrrizk95 avatar amrrizk95 commented on July 19, 2024

i can not append list of objects to my form data i got empty list on the action

$.each(selectLists, function (key, selectList) { var SingelValue = { ItemId: singleList.id, inputValue: singleList.value } SingelValue = JSON.stringify(SingelValue); fdata.append("SingelValues[]", SingelValue) }

from form-data.

FuyaoLi2017 avatar FuyaoLi2017 commented on July 19, 2024

I use Swagger2.0, mongoDB as database and I am trying to go with the stringify() during sending and decode in the Flask server side.
Surprisingly, even though I defined the schema in the swagger UI for such field as string. During get fields, it will still directly get the json array instead of string format... This satisfies my need, but it doesn't make sense. Could someone give me an explanation on this?

from form-data.

abned08 avatar abned08 commented on July 19, 2024

can I append the Object as it is, without Stringify it?

from form-data.

Joserbala avatar Joserbala commented on July 19, 2024

@abned08 no, you may stringify it or use @alexsmartens's solution. FormData.append() only accepts USVString and Blob.

from form-data.

alex-el11 avatar alex-el11 commented on July 19, 2024

Thanks a lot to @alexsmartens for example. I was 3, 4 days without can send objects in FormData post and his example really help me to success.
e.g (C#):
public JsonResult AddTicketUser(TicketViewModel ticketVM) //ticketVM has a Ticket object inside.

I believe that @alexindigo is elegant solution but I not sure how implements in my case. ( Use enctype: 'multipart/form-data' and contentType: false).

greetings :)

from form-data.

garsax avatar garsax commented on July 19, 2024

Following @alexsmartens example here's a handy js function to append an object to FormData

function FormData_append_object(fd, obj, key) {
  var i, k;
  for(i in obj) {
    k = key ? key + '[' + i + ']' : i;
    if(typeof obj[i] == 'object')
      FormData_append_object(fd, obj[i], k);
    else
      fd.append(k, obj[i]);
  }
}

And here's is how you would call it:

var myObject = { a: 'one', b: { b1: 'two', b2: { b21: 'three', b22: 'four' } }, d: 'five' };
fd = new FormData();
FormData_append_object(fd, myObject);

It works great calling ajax from js to PHP.

from form-data.

jorgeramirezamora avatar jorgeramirezamora commented on July 19, 2024

Hey,

The thing is you can send only strings over the wire, so complex data types, like object should be encoded somehow and since there are many way to encode objects, FormData leaves it to developer to choose proper encoding mechanism that supported on the other end. For example it could be a JSON string or a form-urlencoded string.

Something like:

var details = JSON.stringify({age: 12});
form.append('details', details);

Let me know if you have more questions.

In case this is useful for somebody else, in the case you are using Express Multer you can use file.buffer.toString()

from form-data.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.