Connect request-promise module. To send a file I use this code. The code was written schematically so that the question would be clear.
let requestInstance = request.post({uri: uri, json: true}); requestInstance .then(function(response) { // Успешный ответ сервера res.json(response); }) .catch(err => { // На сервере что-то пошло не так res.status(500).json({message: 'some error'}); }); // А вот самое интересное!!! let form = requestInstance.form(); let i = 0; req.files.forEach(f => { form.append('f_' + i, f.buffer, { filename: f.originalname, encoding: f.encoding, mimetype: f.mimetype, size: f.size }); i++; }); // И все! Something I do not understand how this code works. No, that it works correctly is good, the question is how?
I make a request to the server or rather a pre-request, which returns me a promise. Next, I attach files in a loop. And that's all. Where is the method that starts sending data to the server? After all, I never call the method start, send, run and so on. Where is this starting point?
Maybe I misunderstand the essence of the POST request: (
req.files.forEach, where all selected files arereq.files.forEachand added to the request form, after that therequestInstancewill be processedrequestInstancereturning the response from the server. In fact, a strange example - Vasily Barbashevappendmethod is more likely to add data to the form, and the handler sees that not all the data have been processed yet and is waiting for it, after which thethenmethod will be called. Essentiallyappendis yoursend- Vasily Barbashev