axios 用application/x-www-form-urlencoded 传参的正确姿势

Using application/x-www-form-urlencoded format

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 options.

Browser

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);

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).

Alternatively, you can encode data using the qs library:

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

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);

总结:使用URLSearchParams 可能有些浏览器不兼容问题。建议使用qs库。

我们之前项目使用另外一个办法,貌似也可以,大家可以参考:

就是直接在地址后边加参数:url?username=XXX&password=XXXX

 

 

参考:https://segmentfault.com/q/1010000014360170

            https://github.com/axios/axios#browser

你可能感兴趣的:(Java,Web,Develop)