DEV Community

Cover image for How to receive images with the node.js API | fetch , React
off.tokyo
off.tokyo

Posted on

How to receive images with the node.js API | fetch , React

How to receive images with the node.js API | fetch , React - off.tokyo, the web site for high-tech enthusiasts

what i did

The front side is built with React, and the form data is sent to the api by post using JavaScript fetch.

Then, the api receives the form data and saves the data to the server.

To edit the user's information, imagine that the user has to register his name and driver's license (back and front) with the service, and look at the code.

node.js console.log

In the following log, the form data created on the front side is received by post to get the data contained in the request.

At first, I couldn't get the image in the body of the request, so I looked at the log of various requests, and found that the files contained image data.

console.log("use_info")
console.log(JSON.parse(req.body.use_info))

console.log("img_head")
console.log(req.files.img_head)

console.log("img_backkうううううう")
console.log(req.files.img_back)
Enter fullscreen mode Exit fullscreen mode

Front-side implementation fetch

This is the code to post the user's name and image to the api on the front side.

The user data and image data are added by using FormDate and appending to it.

var userData = new FormData()
userData.append('use_info', JSON.stringify(Formdata))
userData.append('img_head', Formdata.fileBack["0"])
userData.append('img_back', Formdata.fileBack["0"])

fetch(`${API_URL}/edit_connect_user`, {
method: 'POST',
body: userData
})
Enter fullscreen mode Exit fullscreen mode

Server-side logs

The following code is the log of the form data thrown from the front side by post.

I think it contains the user's name and image data like this.

use_info
{
firstName: 'Pamyu Pamyu ',
lastName: 'Kyary',
userid: 'fekw020'
}
img_head
{
name: 'img_head.png',
data: ,
size: 9808,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/png',
md5: 'c28358700f3c94f841c7f7fad50596da',
mv: [Function: mv]
}
img_backk
{
name: 'img_backk.png',
data: ,
size: 9808,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/png',
md5: 'c28358700f3c94f841c7f7fad50596da',
mv: [Function: mv]
}
Enter fullscreen mode Exit fullscreen mode

How to receive images with the node.js API | fetch , React - off.tokyo, the web site for high-tech enthusiasts

Top comments (0)