axios transformRequest - how to alter JSON payload

孤人 提交于 2019-12-02 04:35:21

问题


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 where I ran into issues though.

The code I have looks like:

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

      data = {
        SecretStuff: encryptedString,
      };

      return data;
    },
  ],  
});

// firing off my request using the instance above:
const postData = {
    id: 1,
    name: 'James',
};
instance.post('/getStuff', postData)

and ultimately, I want to post api-url.com the JSON: {"SecretStuff": "some-base64-string"} - not the postData object shown above.

From the docs, it says: "The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream" - but of course here I am returning an object, data. Oddly enough in the axios docs it shows them returning data from transformRequest, but in their case that must be the correct data type.

How do I actually transform a payload with axios?


回答1:


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);
        },
    ],  
});



回答2:


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..




回答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');            
        return data;
    },
]
});


来源:https://stackoverflow.com/questions/48819885/axios-transformrequest-how-to-alter-json-payload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!