LoginSignup
5
6

More than 5 years have passed since last update.

Express4でPUTとDELETEを受け取る

Posted at

Express4でPUTとDELETEを受け取る

VIEW側

form(method="post", action="users/#{id}")
  input(type="hidden", name="_method", value="PUT or DELETE")
  input(type="submit", value="Update")

formタグのmethod属性はPUT,DELETEに対応していないのでform内にhidden要素を2行目の様に書く。

middlware側

予め以下をプロジェクトディレクトリにインストールしておく

$ npm install --save method-override
$ npm install --save body-parser

インストールしたらapp.coffeeに以下を追記する。

app.coffee
methodOverrive = require 'method-override'
bodyParser = require 'body-parser'

app.use bodyParser.json()
app.use bodyParser.urlencoded extended: false
app.use methodOverride (req, res) ->
  if req.body? and typeof req.body is 'object' and `'_method' in req.body`
    method = req.body._method
    delete req.body._methodn 
    return method

app.put 'users/:id([0-9]+)', (req, res) ->
  console.log 'PUT'

app.delete 'users/:id([0-9]+)', (req, res) ->
  console.log 'DELETE'

coffeescriptだと'_method' in req.bodyで判定できなくて結構嵌った。
たぶんcoffeeのコンパイラはfor文内のinだと勘違いしてるっぽい?
なのでそこだけ` `で囲んで生のjavascriptを書き込んでる。

これでPUTもDELETEもルーティング出来た!

時代のトレンドはES6みたいだけど、正直まだまだcoffeeのほうが高機能じゃね?と思ってcoffeeを使い続ける。

5
6
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
5
6