When I get the post data in nodejs from Ajax call, it can be displayed in console.log, but when I want to assign it to another variable, or just display on page it turns to [object, object].
Why so?
$.ajax({
type: "POST",
url: 'http://127.0.0.1:5075/testEditmode.html',
'Content-Type': 'application/x-www-form-urlencoded',
data: info2value + '|' + colorvalue + '|'
});
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
app.use(express.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/testEditmode.html', function (req, res) {
// console.log(req.body);
requestData = '';
requestData += req.body;
console.log(requestData.toString());
// console.log(req.body);
var splited = requestData.split("|");
var splitedCoords = requestData.split(",");
Request data = [object, object] but console.log(req.body) displays what it should. toString() didn't help.
What shall I do ?
Namespace data in your jQuery request:
$.ajax({
type: "POST",
json: true, // added this
url: 'http://127.0.0.1:5075/testEditmode.html',
'Content-Type': 'application/x-www-form-urlencoded',
data: {infoValue: info2value + '|' + colorvalue + '|'}
});
You can then do:
requestData = '';
requestData += req.body.infoValue;
If you use the body-parser middleware you are telling express to parse the body of the request and now req.body is an object, so you're actually doing:
var requestData = '' + {}; // "[object Object]" - Same as obj.toString()
and not really mutating req.body, that's why req.body is still an object.