Home > OS >  How to pass an array of data from the client side to req.body of an axios post request
How to pass an array of data from the client side to req.body of an axios post request

Time:11-24

I'm trying to send user data collected in my front end using an ajax call to an axios post request I have set up in my back end. I have a few parameters that require an array of data to be sent back. When I console.log(req.body) in the back end, the data matches up with the variables I have set to req.body, except for the variables that are supposed to take in the array, which are timestamp, values, reason, notes.

postModel: async (req, res) => {
    
        const { analyst, building_number, commodity_tag, meter, timestamp, values, reason, notes } = req.body
   
        console.log(req.body)
     
        try {

           const headers = {
                'Content-Type': 'application/json',
                'authorizationToken': token.token
            }

   
             const postdata = JSON.stringify({
                'analyst': analyst,
                'building_number': building_number,
                'commodity_tag': commodity_tag,
                'meter': meter,
                'data': {
                    'timestamp': [timestamp],
                    'value': [values],
                    'reason': [reason],
                    'notes': [notes]
                }
            })

            const postModel = process.env.POST_API_URL

            const response = await axios.post(postModel, postdata, {
                headers: headers
            })
           
            return res.json(response.data)

        } catch (error) {
            console.error(error.message)
            return res.json(error)
        }

This is req.body logged to the console after data is sent back using the front end ajax call. The four variables that are supposed to be arrays come back in a weird string format, and when I try to use the variable, the value is null so nothing gets passed to the axios data. Or for example if I try to console.log(timestamp) it comes back as undefined, but if I console.log(meter) it gives me the correct value. How do I stop the array data from being sent to my backend in a string format and have it placed into my req.body variable so I can use it in the axios post data?

[Object: null prototype] {
  analyst: '[email protected]',
  building_number: '0227',
  commodity_tag: 'S',
  meter: '2032',
  'timestamp[]': [ '2021-10-05', '2021-10-06', '2021-10-07', '2021-10-08' ],
  'values[]': [ '5830', '6119', '5830', '5830' ],
  'reason[]': [ 'Investigate', 'Investigate', 'Investigate', 'Investigate' ],
  'notes[]': [
    'Testing backend',
    'Testing backend',
    'Testing backend',
    'Testing backend'
  ]
}

This is the front end ajax call. I push data into the four empty arrays and then set those variables in the data values down below.

        let notes = []
        let reason = []
        let values = []
        let timestamp = []
          $.ajax({
                url: '/postGateway',
                method: 'POST',
                data: {
                    analyst: analyst,
                    building_number: building_number,
                    commodity_tag: commodity_tag,
                    meter: meter,
                    timestamp: timestamp,
                    values: values,
                    reason: reason,
                    notes: notes

                },
             
            })

CodePudding user response:

Figured it out. I just had to stringify the data on the front end, and then parse it on the back end. Like this:

Front end ajax call. I JSON.stringify the array data.

 $.ajax({
                url: '/postGateway',
                method: 'POST',
                data: {
                    analyst: analyst,
                    building_number: building_number,
                    commodity_tag: commodity_tag,
                    meter: meter,
                    timestamp: JSON.stringify(timestamp),
                    values: JSON.stringify(values),
                    reason: JSON.stringify(reason),
                    notes: JSON.stringify(notes)

                },
})

And then I parse the req.body variables in the back end. And now my data submits perfectly!

const postdata = JSON.stringify({
                'analyst': analyst,
                'building_number': building_number,
                'commodity_tag': commodity_tag,
                'meter': meter,
                'data': {
                    'timestamp': JSON.parse(timestamp),
                    'value': JSON.parse(values),
                    'reason': JSON.parse(reason),
                    'notes': JSON.parse(notes)
                }
            })
  • Related