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

查看:25
本文介绍了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 文档中,它显示他们从 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天全站免登陆