1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jQueryによるajax通信時、Nest.jsサーバ側の型バリデーションで詰まったので備忘録

Posted at

概要

フロント側からjQuery.ajaxでNestJsサーバーの方へリクエストを送った際に、
型が全てstringになってしまいバリデーションが機能しないことがあったのでその解決策。

解決策

jQuery.ajax側で、以下の2点を明示して渡す。
・contentTypeを"application/json"に設定
・bodyをJSON.stringifyで括る

sample.js
$.ajax({
    type  : "Get",
    url   : "https://unko.com",
    contentType : "application/json",
    timeout  : 1000,
    data  : JSON.stringify(obj)
    }).done()
)}

原因

jQuery.ajaxはデフォルトで 1 "application/x-www-form-urlencoded"で送られるため。(クエリ形式)
注意点として、JSON.stringify()をしたからといって、Nest側で明示的にparseする必要はなく、例えば以下のような設定によって受け取り時にパースされる。

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

処理としてはここらへんになるが、この時"application/jsonを明示しないと、狂ったオブジェクトとして返ってくるので注意。(ここでハマった。)

  1. http://semooh.jp/jquery/api/ajax/jQuery.ajax/options/

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?