Good day,

I can not figure out how to properly handle a POST request with multiple tags.

There is a POST request from the browser to add a book, the array looks like this:

id:1 header: Kolobok ...:...//ΠΈ Ρ‚.Π΄. genre1: Π΄Ρ€Π°ΠΌΠΌΠ° genre2: ΠΏΡ€ΠΈΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ 

etc. unknown number of genres (how many the user will choose).

So, this array comes to the server (node.js) and to send to the database a request for adding the form: INSERT INTO genre ( genre_id ), ( genre_id ), ( genre_id ) // etc, depending on the number of genres

It is necessary to pull out the records starting with the genre from POST and count their number.

 Object.getOwnPropertyNames(req.body).forEach(function(val, idx, array) { if (val == true) {console.log(val + ' -> ' + req.body[val]);} }); 

Actually the question is how to compare val (this will be the key) with the string genre (1-20)?

And in general, can there be a simpler way?

  • 2
    Hmm, why send a lot of similar keys? From the form you can quite normally send a post to an array genre [] - sepgg

1 answer 1

And in general, can there be a simpler way?

There is. On the client to send a normal post-request. Both POST and GET support arrays, so there is no problem in sending a POST request of the form:

 genres[0]: ΠΏΡ€ΠΈΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ genres[1]: фантастика genres[2]: Π΄Π΅Ρ‚Π΅ΠΊΡ‚ΠΈΠ² 

Then, respectively, access to the elements as to a regular array.

If you submit a form without using JS, then in HTML this is achieved using

 <input name="genres[0]" value="ΠΏΡ€ΠΈΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ"> 

If you submit the form via JS, then I think there shouldn't be any special questions.