Eleanor hill Elly
Eleanor hill Elly

Reputation: 15

React, node js, mongoDB - How to make post, put, delete with FormData?

How to create a post service with formdata?

I sent formdata by Axios. However, the value of 'req.body.title' on the node-express server is empty. So now I am sending fetch in the following format. But I need to upload the file to the server, so I want to send it using formData.

let bodys = 'title=a1&contents=b'
fetch("http://localhost:5000/test", {
            method : 'post',
            headers : {
                'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: bodys
        })
        .then(function(response){
            console.log('Request Succeded ', response);
        })
        .catch(function (error){
            console.log('Failed ', error)
        })

I wrote new data using append with new FormData(), I checked that FormData contains a value on React. However, the node-express server did not enter the body.

please let me know what to do...

Upvotes: 1

Views: 1092

Answers (2)

oosniss
oosniss

Reputation: 460

Try sending FormData object instead of raw string as your request body.

const bodys = new FormData();

bodys.append('title', 'a1');
bodys.append('contents', 'b');

This form data will be available in request.body in express.js server.

Edit: to parse the FormData in express.js, you need a middleware like multer

const upload = require('multer');

app.use('/', upload.any(), yourRouteHandler);

Upvotes: 1

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

You are sending just a string so

You can access your body like below

  let bodys = 'title=a1&contents=b'
 console.log(req.body); //will print title and contents as you are sending

If you want to access title and contents separately then you have to send data as an object

  const bodys = {“title”: “a1”, “contents”: “b”}
  console.log(“title”, req.body.title); //will print a1
  console.log(“contents”, req.body.contents); //will print b

Chec this thread for more details https://github.com/github/fetch/issues/263

Upvotes: 0

Related Questions