Skip to content
Advertisement

How to pass data in body in get type Api in react.js?

I am trying to pass data in body of get type Api in react.js app. I am using the following code. But Api doesn’t get any data.

getUnits = ( key, text, code, limit, offset ) => {
                let data = JSON.stringify( { unit: { key, text, code, limit, offset } } );
                let config = {
                    method: 'get',
                    url: BaseURL + 'unit',
                    headers: { 'Content-Type': 'application/json' },
                    data: data
                };
                axios( config ).then( res => {
                        store.dispatch( {
                            type: GET_UNIT,
                            payload: res.data.units
                        } )
                } ).catch( err => {
                    console.log(err);
                })
            })
        }

Advertisement

Answer

Adding on what @Jayna commented, you can’t send a body with a get request. You may do it on Postman and generate the axios code for it, but it won’t work due to the XMLHTTPREQUEST javascript has. Body is ignored in get request by default

1You need to pass params instead like this:

                let config = {
                    method: 'get',
                    url: BaseURL + 'unit',
                    headers: { 'Content-Type': 'application/json' },
                    params: {
                      field1: 'field1',
                      field2: 'field2'
                    }
                };

So my suggestion is change your url on backend to accept query parameters and send the axios get request like this.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement