0

Somehow I realized that when I pass array of numbers to the backend expressjs I I would get array of strings instead of numbers.

This is the ajax code for sending the data

$.ajax({
    method: 'post',
    url: this.url.ajax.send,
    data,
})

This is the values I have in frontend passing to backend

const data = {
  "type": [
    1,
    2
  ],
  "to": [
    0
  ],
  "message": "testing message here"
}

this is what I get in my backend req.body

{ type: [ '1', '2' ],
  to: [ '0' ],
  message: 'testing message here' } 

I do have bodyParser setup like such

app.use(bodyParser.urlencoded({
    extended: true,
    parameterLimit: 2000000,  // too many parameter if not set
    limit: 1024 * 1024 * 10  // entity too large if not set
}));
app.use(bodyParser.json({
    extended: true,
    parameterLimit: 2000000,  // too many parameter if not set
    limit: 1024 * 1024 * 10  // entity too large if not set
}));

Is this normal or any way I can fix it?

EDIT: This is an image I see from network tab in chrome's inspect tool enter image description here

8
  • can you show how are you sending the data? Commented Jul 31, 2019 at 18:58
  • Try making a similar request using Postman (or curl) to your backend and let me know if it still happens. Commented Jul 31, 2019 at 19:00
  • @MohammedAmirAnsari edited, a jquery ajax call Commented Jul 31, 2019 at 19:02
  • @UtkarshPramodGupta my bad, I did test with postman and with postman it was fine that backend reads as array of numbers. But what I posted above for const data = is what I console.log the values right before ajax call though Commented Jul 31, 2019 at 19:02
  • @Dora don't console.log, check in the network request using browser's dev tools what is actually being sent to the backend. Commented Aug 1, 2019 at 3:48

1 Answer 1

1

parse the string to int with parseInt, example :

let requestBody = {
  type: [ '1', '2' ],
  to: [ '0' ],
  message: 'testing message here'
}

requestBody.type = requestBody.type.map((arr) => {
  arr = parseInt(arr)
  return arr
})

requestBody.to = requestBody.to.map((arr) => {
  arr = parseInt(arr)
  return arr
})

console.log(requestBody)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.