乐闻世界logo
搜索文章和话题

How to alter JSON payload using axios transformRequest

1个答案

1

In Axios, transformRequest allows you to modify the request data before it is sent to the server. This can be used to change the format of the request body, add or modify request headers, or implement any other actions you want to perform before sending the request.

For example, suppose we have a POST request sending JSON data to the server. We can use transformRequest to transform this data, such as wrapping it in a specific object structure before sending:

javascript
const axios = require('axios'); // Assume the original data to be sent is as follows const dataToSend = { name: "张三", email: "zhangsan@example.com" }; // Create Axios request configuration const config = { method: 'post', url: 'https://example.com/api/users', data: dataToSend, transformRequest: [(data, headers) => { // Here, we can modify the request headers headers['Content-Type'] = 'application/json'; // Transform the request data structure const transformedData = { userData: data, additionalInfo: "This is some additional information" }; // Must return a string or ArrayBuffer, FormData, etc. return JSON.stringify(transformedData); }] }; // Send the request axios(config) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); });

In this example, we create a basic Axios request configuration and define a transformRequest function. This function receives the original data and request headers as parameters. Inside the function, we modify the request headers (here, setting 'Content-Type' to 'application/json'), then transform the data structure by wrapping the original data in a new object's userData property and adding an additionalInfo property. Then we convert this new object to a JSON string and return it.

Note that transformRequest is an array of functions, so you can provide multiple transformation functions in sequence, each of which can operate on the data and return new data to the next function.

In practical applications, using transformRequest can flexibly address various needs, such as encrypting data, removing unnecessary data fields, or adding additional validation information.

2024年6月29日 12:07 回复

你的答案