0

I use HttpClient in Angular to send formdata to Nodejs.

 resetPasswordRequest(email){
    this.httpOptions={
      headers: new HttpHeaders({
        'Content-Type':'application/x-www-form-urlencoded'
      })
    }

    const formData = new FormData();

     formData.append('email',email);

    return this.http.post("http://localhost:3001/forgotPassword",formData,this.httpOptions);

  }

Later in NodeJS,I have app.use(bodyParser.urlencoded({extended:true}).

I am able to get req.body but in a different format as below:

{ '-----------------------------24875245787704\r\nContent-Disposition: form-data; name':
   '"email"\r\n\r\abcd@gmail.com\r\n-----------------------------24875245787704--\r\n' }

I am not sure what has been missed. Could you please clarify and help get value of email? I get req.body.email as undefined.

Gayathri
  • 1,776
  • 5
  • 23
  • 50

2 Answers2

0

you need to parse formData in nodejs. see this question or find similar. also are you sure you need to use formData? you can just send object in body

chestas
  • 124
  • 1
  • 6
0

From MDN FormData:

It uses the same format a form would use if the encoding type were set to "multipart/form-data"

which explains why you're getting data in that format.

You could use angular's HttpParams instead:

const formData = new HttpParams();
formData.set('email', email)

return this.http.post("http://localhost:3001/forgotPassword", formData.toString(), this.httpOptions);

toString gives you urlencoded format. From docs:

Serialize the body to an encoded string, where key-value pairs (separated by =) are separated by &s

1565986223
  • 6,420
  • 2
  • 20
  • 33
  • just to confirm. how do you get value of it in NodeJS? I get req.params as {} , req.body as {} , req.query as {} – Gayathri May 05 '19 at 10:58
  • `req.body` should contain the data what do you get if you `console.log(formData.toString())` frontend – 1565986223 May 05 '19 at 11:28
  • thanks for asking to check console log. later https://stackoverflow.com/questions/45500264/angular-4-3-httpclient-get-params-empty helped. And am able to get data properly. – Gayathri May 19 '19 at 12:56