javascript axios transformRequest - 如何更改 JSON 有效负载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48819885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
axios transformRequest - how to alter JSON payload
提问by james
I am using axiosin 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.
我在 Express API 中使用axios,我想在将其发送到另一个 API 之前转换有效负载。axios 正好有这个叫做transformRequest. 不过,这就是我遇到问题的地方。
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.comthe JSON: {"SecretStuff": "some-base64-string"}- not the postDataobject shown above.
最终,我想发布api-url.comJSON: {"SecretStuff": "some-base64-string"}- 不是postData上面显示的对象。
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 datafrom transformRequest, but in their case that must be the correct data type.
从文档中,它说:“数组中的最后一个函数必须返回一个字符串或一个 Buffer、ArrayBuffer、FormData 或 Stream 的实例”——但当然这里我要返回一个对象,数据。奇怪的是,在 axios 文档中,它显示它们data从返回transformRequest,但在它们的情况下,必须是正确的数据类型。
How do I actuallytransform a payload with axios?
如何使用 axios实际转换有效负载?
采纳答案by Varinder
Wouldn't you want to JSON.stringify()your transformed post data? Like below:
您不想使用JSON.stringify()转换后的帖子数据吗?像下面这样:
const instance = axios.create({
baseURL: 'api-url.com',
transformRequest: [
(data, headers) => {
const encryptedString = encryptPayload(JSON.stringify(data));
data = {
SecretStuff: encryptedString,
};
return JSON.stringify(data);
},
],
});
回答by Kevin
axios.create({
transformRequest: [(data, headers) => {
// modify data here
return data;
}, ...axios.defaults.transformRequest]
});
have to append the original axios.defaults.transformRequestto the transformRequestoption here..
必须将原件axios.defaults.transformRequest附加到transformRequest此处的选项中..
回答by Miguel Puig
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;
},
]
});

