simply way to handle post data/image in node js through Postman Form-Data - node.js

Is there a way to post form-data through postman using Nodejs. I have seen many platforms but the author is using the front-end to post data which manipulates the back-end code. I want to understand the code

Yes you can send the data using form-data in post man.
You can see the formdata under the body section in this form data you have to change the type from text to file
after changing to file type you can browse your local machine. to choose the image
You can further parse the files in node js using formidable. You can install this package and you can configure to your needs. It can handle upto 1000 files
Coming to code part in node js.
First configure the formidable
const form = new formidable.IncomingForm({
multiples: true,
keepExtensions: true,
});
After that you have to parse the fieldvalue and file
form.parse(req);
Then you can seperate the value and files uisng
form.on("file", (field, file) => {}) //For file
form.on("field", (fieldName, fieldValue) => {}) //for fieldvalue
Hope this one helps for you!!

Sure thing. Set request type to POST and then define your data in the request body
check this out
https://learning.postman.com/docs/sending-requests/requests/#sending-body-data

Related

How could I save an img in my express server that I receive from my client?

I have a client in React that sends a form data with a file. When that file arrives to the server, the body is parsed by body parser and its result is a buffer. The idea is that the file keep saved in some place of my server, because I want to use it later from my client. So I'd like to know how should I handle this problem.
I tried to write directly this buffer as a file with fs, but the file created has an error of format, so I can't access it.
You can do stuff like this
var fs = require('fs');
fs.writeFile('newImage', req.files.image, function (err) {
if (err) throw err;
console.log("It's saved");
});
correct parameter order of fs.writeFile is the filename first then the content.
If you're using express.bodyParser() you'll have the uploaded files in the req.files field.
And of course you should write the callback:
POV: Your image file should be in req.files not the body.
I think you need a package for storing a file on your backend service. I had used morgan package for that and I was satisfied with using it. I have just searched other packages for storing a file, i found express-fileupload package. Maybe you want to look at how to use those. If you want to store a file, using the third package would be better for you and for your effort.

NodeJs with Express not parsing form data from node-fetch

I'm creating two APIs with NodeJS, Express, and TypeScript. One API will take a request with a content type of multipart/form-data, and will use the body in the request to make another request to a second API.
I'm using Postman, so the chain of request looks something like this
Postman -> First API -> Second API
I use node-fetch to make a request from the first API to the second one. The body of the request is a FormData, which contains some files and key-value pairs.
const form = new FormData();
// File for profile picture
const profilePictureBuffer = await (await fetch(user.profilePicture)).buffer();
form.append('profilePicture', profilePictureBuffer);
// File for ID Card
const idCardBuffer = await (await fetch(user.idCardUrl)).buffer();
form.append('idCard', idCardBuffer);
// This part iterats over the obsect of 'user',
// which contains other key-value pairs
Object.entries(user).forEach((data) => {
form.append(data[0], data[1]);
});
// Make POST request to second API
const pinterUser = await fetch(secondAPIURL, {
method: 'post',
body: form,
headers: form.getHeaders()
});
I ran both of the APIs on localhost so that I can monitor the logs for any bugs. As I make a request from Postman to the first API, then the first API make another request to the second API, I got the following error log in the terminal for the second API
TypeError: Cannot read property '0' of undefined
After some investigation, I found out that, in the second API, the req.body and req.files are empty objects. This means that Express did not parse the incoming request. Note that I've also already a multer middleware to handle the files in the request.
Furthermore, I have added the following lines of code in my server.ts file for the second API
/** Parse the body of the request */
router.use(express.urlencoded({ extended: true }));
router.use(express.json());
However, when I tried making the request from Postman, it returns a successful response.
I'm not really sure what's going on here. I've tried looking for some answer regarding this similar issue, but most of them suggest adding urlencoded and json, or using some other library to handle parsing form data.
In my case, the first suggestion doesn't solve my problem since I already added them from the start, and the latter is what I'm trying to avoid.
I wonder if anybody could point out what I was missing here? Thanks in advance

FormData throws Network Error All the time

I am trying to upload a file to my NodeJs Server from My Mobile ReactNative App.
I tried to use FormData with Axios post but it is resulting in a NetworkError. Logging the FormData object before sending it gives me an object with an Array _parts that contains Arrays of my fields.
Also when I console.log the prototypes of FormData I only get two methods that I can use, which are append and getParts. I can't use any method that does exist in the documentation like getHeaders or getBoundary
Now If I want to make a file upload without using FormData, Should I send a fileStream of the picture I want to upload or just send the uri of the picture? I am using multer to capture the Files in my server.
What was causing the Network Error is me using a nested object inside dataForm.
//Other code onTop
const {location, ...other} = payload;
form.append("location", JSON.stringify(location));
...
I hope this might help someone.
Also Files Are Blobs, basically a readabaleStream. Read More About it Here

formData through http.post in angular + nodejs

I'm facing an issue when I want to pass some data through http.post from my angular client to my node.js server.
Here is the thing, passing text with JSON.stringify(my text) works fine, but given that I want to pass a file + my text, I would like to use formData.
When I try to get back the data in the server side, my req.body is empty, and i'm not able to retrieve the data.
Here is my client side code :
[...]
var formData = new FormData();
formData.append('name', product.name);
formData.append('benefits_detail', product.benefits_detail);
formData.append('sections', product.sections);
formData.append('image', product.image); // image is my file
return this.http.post('http://localhost:3000/product', formData, {headers: headers}).map(........)
Then my server, where I try to get back my data :
router.post('/', function (req, res, next) {
console.log('req.body');
console.log(req.body);
console.log(req.body.formData);
...
Here the console.log are empty like showing : {}
Anybody can help with this ?
Thanks you
It looks like you're not using any body parsing middleware, which is required.
From the Express documentation for req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
Try using body-parser
For uploading images to a server, you could try to use the Ng File Upload directive. It has a directive to select the file in HTML and then to Upload the file to the server. If you are already selecting the image, I believe you can just use the Uploading part in JS to send the image (have never tried using the Upload without the file selector in HTML, but It should work).
However, this solution would require you to send two requests though, one for the data and another for the image.

How to parse Multi-part form data in an Azure Function App with HTTP Trigger? (NodeJS)

I want to write a NodeJS HTTP endpoint using Azure Functions.
This endpoint will be a POST endpoint which takes files and upload these to blob storage.
However, NodeJS multipart form data parsers are all in the form of httpserver or expressJS middleware.
Is there any available tools that can parse the multipart form data after it has all been received from the Function Application's wrapper?
Thanks!
To answer original question:
However, NodeJS multipart form data parsers are all in the form of
httpserver or expressJS middleware.
Is there any available tools that can parse the multipart form data
after it has all been received from the Function Application's
wrapper?
Even 2 years later after you asked this question state of multipart form data parsers is not great, like you noticed majority of them assume req object which is a stream and tutorials/demos show how to parse multipart/form-data with express or httpServer.
However there is a parse-multipart npm package which can process req.body from azure function and return you array of objects with code similar to following:
const multipart = require("parse-multipart");
module.exports = function (context, request) {
context.log('JavaScript HTTP trigger function processed a request.');
// encode body to base64 string
const bodyBuffer = Buffer.from(request.body);
const boundary = multipart.getBoundary(request.headers['content-type']);
// parse the body
const parts = multipart.Parse(bodyBuffer, boundary);
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: parts[0].data.length}};
context.done();
};
(original source: https://www.builtwithcloud.com/multipart-form-data-processing-via-httptrigger-using-nodejs-azure-functions/)
One area where I noticed parse-multipart can struggle is parsing forms with text fields. A slightly improved version which handles it better is called multipart-formdata:
require('multipart-formdata').parse(req.body, boundary)
//returns [{field, name, data, filename, type}, ...] where data is buffer you can use to save files
As Azure Functions has wrapped http server object in Node.js, and exposes a simple req and context with several functionalities, refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#exporting-a-function for details.
And mostly, Azure Functions is designed for triggers and webhooks requests, you can refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-compare-logic-apps-ms-flow-webjobs for the detailed comparison.
Meanwhile, you can try the answer of Image upload to server in node.js without using express to parse the request body content to file content, and upload to Azure Storage leveraging Azure Storage SDK for node.js, you can install custom node modules via KUDU console. Refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#node-version--package-management for more info.
And I suggest you can try to leverage Azure API App in node.js to approach your requiremnet. As it is an expressjs based project, which will be more easier to handle upload files.
Any further concern, please feel free to let me know.
I have good experiences with the new azure-function-multipart package. Example code might look like this:
const {
default: parseMultipartFormData,
} = require("#anzp/azure-function-multipart");
module.exports = async function (context, req) {
const { fields, files } = await parseMultipartFormData(req);
console.log("fields", fields)
console.log("files", files)
};
See docs for more details.
You can try to use this adapter for functions and express, it may allow you to successfully use the multi-part middleware you want: https://github.com/yvele/azure-function-express
As a less desirable option, you can parse the body yourself, all the multi-part data will be available in req.body and will look something like this:
------WebKitFormBoundarymQMaH4AksAbC8HRW
Content-Disposition: form-data; name="key"
value
------WebKitFormBoundarymQMaH4AksAbC8HRW
Content-Disposition: form-data; name=""
------WebKitFormBoundarymQMaH4AksAbC8HRW--
I do think it's a good idea to support httpserver / express better in order to enable this extensibility.

Resources