axios post request to send form data

后端 未结 9 2283
走了就别回头了
走了就别回头了 2020-11-22 03:40

axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload conta

9条回答
  •  终归单人心
    2020-11-22 03:58

    Using application/x-www-form-urlencoded format in axios

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

提交回复
热议问题