URL 编码的主体

默认情况下,axios 将 JavaScript 对象序列化为 JSON。要改为以 application/x-www-form-urlencoded 格式发送数据,你可以使用以下方法之一。

¥By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following approaches.

浏览器

¥Browser

在浏览器中,你可以按如下方式使用 URLSearchParams API:

¥In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

请注意,并非所有浏览器都支持 URLSearchParams(请参阅 caniuse.com),但有一个 polyfill 可用(确保填充全局环境)。

¥Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

或者,你可以使用 qs 库对数据进行编码:

¥Alternatively, you can encode data using the qs library:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

或者以另一种方式(ES6),

¥Or in another way (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

Node.js

查询字符串

¥Query string

在 node.js 中,你可以像下面这样使用 querystring 模块:

¥In node.js, you can use the querystring module as follows:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

'url 模块' 中的 'URLSearchParams',如下所示:

¥or 'URLSearchParams' from 'url module' as follows:

const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());

你还可以使用 qs 库。

¥You can also use the qs library.

注意:如果你需要对嵌套对象进行字符串化,则 qs 库更可取,因为 querystring 方法在该用例 (https://github.com/nodejs/node-v0.x-archive/issues/1665) 中存在已知问题。

¥Note: The qs library is preferable if you need to stringify nested objects, as the querystring method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

🆕 自动序列化

¥🆕 Automatic serialization

如果 content-type 标头设置为 application/x-www-form-urlencoded,axios 会自动将数据对象序列化为 urlencoded 格式。

¥Axios will automatically serialize the data object to urlencoded format if the content-type header is set to application/x-www-form-urlencoded.

这在浏览器和 node.js 中都有效:

¥This works both in the browser and in node.js:

const data = {
  x: 1,
  arr: [1, 2, 3],
  arr2: [1, [2], 3],
  users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
};

await axios.post('https://postman-echo.com/post', data,
  {headers: {'content-type': 'application/x-www-form-urlencoded'}}
);

服务器将处理它作为

¥The server will handle it as

  {
    x: '1',
    'arr[]': [ '1', '2', '3' ],
    'arr2[0]': '1',
    'arr2[1][0]': '2',
    'arr2[2]': '3',
    'arr3[]': [ '1', '2', '3' ],
    'users[0][name]': 'Peter',
    'users[0][surname]': 'griffin',
    'users[1][name]': 'Thomas',
    'users[1][surname]': 'Anderson'
  }

如果你的服务器框架的请求主体解析器(如 body-parserexpress.js)支持嵌套对象解码,你将自动收到与你提交的相同的服务器对象。

¥If your server framework's request body parser (like body-parser of express.js) supports nested objects decoding, you will automatically receive the same server object that you submitted.

回声服务器示例(express.js):

¥Echo server example (express.js) :

  var app = express();
  
  app.use(bodyParser.urlencoded({ extended: true })); // support url-encoded bodies
  
  app.post('/', function (req, res, next) {
     res.send(JSON.stringify(req.body));
  });

  server = app.listen(3000);