axios transformRequest - 如何更改JSON有效负载 [英] axios transformRequest - how to alter JSON payload

查看:657
本文介绍了axios transformRequest - 如何更改JSON有效负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Express API中使用 axios ,我希望在发送之前转换有效负载到另一个API。 axios就是这个名为 transformRequest 。这是我遇到问题的地方。

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.

我的代码如下:

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)

最终,我想要发表 api-url.com JSON: {SecretStuff:some-base64-string} - 不是上面显示的 postData 对象。

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

从文档中,它说:数组中的最后一个函数必须返回一个字符串或Buffer,ArrayBuffer,FormData或Stream的实例 - 当然,我在这里返回一个对象,数据。在axios docs中奇怪的是,它显示它们从 transformRequest 返回 data ,但在他们的情况下必须是正确的数据类型。

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.

我如何实际使用axios转换有效负载?

How do I actually transform a payload with axios?

推荐答案

你不想 JSON.stringify()你的转换后的数据?如下所示:

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

这篇关于axios transformRequest - 如何更改JSON有效负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆