formData through http.post in angular + nodejs - node.js

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.

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.

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

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

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

How can I build a web app that I can send files to for further manipulation?

I want to build a NodeJS server that accepts a .wav file (1Mb) sent to its single endpoint, then changes the file through AudioContext API and then sends back the response with the result?
The server shouldn't store anything, so, no database required.
How can I achieve this? (or, please correct me if don't understand how things work)
I would do this with express: https://expressjs.com/
and as middleware add express-fileuplaod: https://www.npmjs.com/package/express-fileupload
app.post('/upload', function(req, res) {
console.log(req.files.foo); // the uploaded file object
});
instead of the console.log(); you'd make a readable stream / buffer and then use it in the
AudioContext API
here is also a interesting Article explaining to use this:
https://www.russellgood.com/process-uploaded-file-web-audio-api/

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

Resources