Skip to content Skip to sidebar Skip to footer

Axios Transformrequest - How To Alter Json Payload

I am using axios in my Express API and I want to transform the payload before sending it off to another API. axios has just the thing for this called transformRequest. This is wher

Solution 1:

axios.create({
    transformRequest: [(data, headers) => {
        // modify data herereturndata;
    }, ...axios.defaults.transformRequest]
});

have to append the original axios.defaults.transformRequest to the transformRequest option here..

Solution 2:

Wouldn't you want to JSON.stringify() your transformed post data? Like below:

const instance = axios.create({
    baseURL: 'api-url.com',
    transformRequest: [
        (data, headers) => {
            const encryptedString = encryptPayload(JSON.stringify(data));

            data = {
                SecretStuff: encryptedString,
            };

            return JSON.stringify(data);
        },
    ],  
});

Solution 3:

To amend the values instead of override the output in the request I would do this:

const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
    (data, headers) => {
        data.append('myKey','myValue');            
        returndata;
    },
]
});

Post a Comment for "Axios Transformrequest - How To Alter Json Payload"