1

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...

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

As oosniss points out, you'll need some middleware that parses multipart/form-data. Libraries, like bodyParser, do not handle this MIME type and therefore form data won't show up on req.body.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.