Works by

Ren's blog

@rennnosuke_rk 技術ブログです

【AngularJS】$httpでformによるPOSTリクエストを再現する

AngularJSの$httpメソッドでHTTPリクエストを発行する時、
コンテンツの形式をサーバ側と一致させなければサーバ側に正しくデータを受け取ってもらえない。

例えば、サーバ側がformタグのsubmitによってデータが送られていること想定しているとする。

HTML
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>input test</title>
</head>
<body>
  <form name="form-example" method="get" action="hoge/fuga">
    <input id="input-tel" name="inputTel" type="tel"/>
    <input type="submit" value="submit"/>
  </form>
</body>
</html>
Server(JavaEE servlet)
public class HogeServlet extends HttpServlet {

  @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // パラメータを取得
    String inputTel = request.getParameter("inputTel");
    //...
  }
}

このとき、formを使わずに他の方法でHTTPリクエストを送りたいのであれば、formと同じデータタイプを明示的に指定する必要がある。

angular.module('myApp',[])
.controller('myController', [function(){

  // request
  $http.get(
    url: 'hoge/fuga',
    method: 'get',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    data: {}
  );

}]);

上記コードはAngularJSでformと同じ形式のHTTPリクエスト送出を表している(おそらく$httpの仕様で、他のヘッダ属性で違うところもあるが)。

デフォルトのformタグは、HTTPヘッダのContent-Typeapplication/x-www-form-urlencodedを設定する。任意のHTTPクライアントでformと同様のリクエストを送りたい場合は、同じようにHTTPヘッダのContent-Typeを編集する必要がある。

参考文献

- HTML | MDN