LoginSignup
53
37

More than 5 years have passed since last update.

axios で POST する際、Content-type を application/x-www-form-urlencoded にしたい時どうするか

Posted at

経緯

axios (Javascript の Promise based HTTP client) で Postしたい。
・Defaultでは Post Parameter は JSON 形式で送信されるが、Formで入力されたときとと同じパラメータ形式としたい。
・Option で Content-type を application/x-www-form-urlencoded に変更しただけでは、うまくいかない。
 Json形式で送信されている様子

【だめだった例】

    axios.post('/test', { param1: '1', param2: 'test' }, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .then(function() {
           ....
        })
        .catch(function() {
           ....
        });

解決策

・URLSearchParams を使ってパラメータを構築する。

【よい例】

    var params = new URLSearchParams();
    params.append('param1', '1');
    params.append('param2', 'test');

    axios.post('/test', params)
        .then(function() {
           ....
        })
        .catch(function() {
           ....
        });

教訓

やっぱり、ざっとでもいいので、マニュアルを 最後まで 見ましょう!!

53
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
37