Reputation: 59
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.
Upvotes: 1
Views: 1502
Reputation: 48968
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.
Upvotes: 0
Reputation: 4748
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.
Upvotes: 2