axios transformRequest - how to alter JSON payload

后端 未结 3 678
日久生厌
日久生厌 2021-01-05 17:10

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

相关标签:
3条回答
  • 2021-01-05 17:36

    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');            
            return data;
        },
    ]
    });
    
    0 讨论(0)
  • 2021-01-05 17:43

    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);
            },
        ],  
    });
    
    0 讨论(0)
  • 2021-01-05 17:53
    axios.create({
        transformRequest: [(data, headers) => {
            // modify data here
            return data;
        }, ...axios.defaults.transformRequest]
    });
    

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

    0 讨论(0)
提交回复
热议问题