Reputation: 11
Okay, this seems to be the most straight forward thing, but I really have no idea why it's doing this nor find anyone else with this problem.
Here's my issue, I'm sending a POST request like so;
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
In the data object is an array called items
. When I log the data object it's fine, like it should be, however when I log the data object in my express function the items
array changes to items[]
for no reason..
NodeJS
'items[]': '15716345'
JS (Browser)
items: [15716345]
Any idea what's happening here?
Below is the entire version of the code. Entire block (frontend) // Validate address if($('.block.payment .wrapper input:eq(0)').val() !== $('.block.payment .wrapper input:eq(1)').val()){ return error('Fields do not match'); }
// Get known data
var type = $('.body.inventory .methods .method.selected').data('type'),
items = [];
var data = {
type,
address: $('.block.payment .wrapper input:eq(0)').val()
}
if(type === 'steam'){
var app = $('.body.inventory .sub-methods .method.selected').data('app');
data['app'] = app;
$('.body.inventory .item[data-app="'+app+'"].selected').each(function(){
items.push($(this).data('id'));
});
}else{
$('.body.inventory .item[data-type="'+type+'"].selected').each(function(){
items.push($(this).data('id'));
});
}
data['items'] = items;
// Execute route or smt
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Backend
router.post('/sell', function(req, res, next) {
try {
console.log(req.body);
res.send({
success: 1
});
} catch(e) {
if(e) console.log(e);
res.send({
success: 0,
error: e
});
}
});
Upvotes: 0
Views: 1115
Reputation: 101
object[] Obj = new object[1];
Obj [0] = "value1"
Obj [1] = "Value2"
Obj [3] = {"CollectionValue1, CollectionValue2"}
$.ajax({
url: '../Controller/MethodName',
type: 'post',
datatype: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ControllerParameterName: Obj }), <!-- Obj is your Array -->
success: function (data) {
alert(data.Response);
}
});
Upvotes: 0
Reputation: 38922
Set JSON
body parser middleware for requests to your expressJS application.
const bodyParser = require('body-parser');
app.use(bodyParser.json())
And in the AJAX request, make the contentType
to be application/json
and not the default of application/x-www-form-urlencoded; charset=UTF-8'
.
$.ajax({
contentType: 'application/json',
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Upvotes: 1