1

I posted data on angular front end as formData like this.

postButton(name: string): Observable<any> {
    const formData = new FormData();
    formData.append('name', name);
    return this.http.post(environment.apiUrl + '/url, formData);
}

And I receive data on Node.js front end like this.

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/url', (req, res, next) => {
  console.log(req.body)
  res.status(200).json({
    'message': 'OK',
  });
});

But I get {},empty value. what is wrong in my code? Regards.

2 Answers 2

2

According to my knowledge, if you are sending some file then using FormData is useful. In other scenario's like this in which you are just sending plain text. You can just send a normal json object and it will work. You can try this.

postButton(name: string): Observable<any> {
  return this.http.post(environment.apiUrl + '/url, { name });
}

In case you really want to use FormData then you need to install a npm package as:

npm install multer

And change your app.js to:

var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer();

app.use(express.json()); 
app.use(express.urlencoded({ extended: true })); 
app.use(upload.array()); 
app.use(express.static('public'));

app.post('/api/url', function (req, res) {
    console.log(req.body);
});

module.exports = app;

Now, what multer does is, it supports multi-part form submission. And FromData uses that. To get the data from request body you need to install and configure multer.

Hope this works for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer, but I tried like that way and that works correctly. But I should to send data with form data.
@JordanMicle Answer Updated
Great, it works correctly, Thanks for your help, Muhammad
0

Delete the Content-Type header:

postButton(name: string): Observable<any> {
    const formData = new FormData();
    formData.append('name', name);

    const httpOptions = {
      headers: new HttpHeaders().delete('Content-Type')
    };

    return this.http.post(environment.apiUrl + '/url, formData, httpOptions);
}

When the XHR API send method sends a FormData Object, it automatically sets the content type header with the appropriate boundary. When the Angular http service overrides the default content type, the server will get a content type header without the proper boundary.

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.