File tree Expand file tree Collapse file tree 2 files changed +40
-4
lines changed
Expand file tree Collapse file tree 2 files changed +40
-4
lines changed Original file line number Diff line number Diff line change @@ -298,16 +298,28 @@ class Web {
298298 // flash messages
299299 app . use ( flash ( ) ) ;
300300
301- // method override
302- // (e.g. `<input type="hidden" name="_method" value="PUT" />`)
303- app . use ( methodOverride ( ) ) ;
304-
305301 // body parser
306302 app . use ( bodyParser ( ) ) ;
307303
308304 // pretty-printed json responses
309305 app . use ( json ( ) ) ;
310306
307+ // method override
308+ // (e.g. `<input type="hidden" name="_method" value="PUT" />`)
309+ app . use (
310+ methodOverride ( req => {
311+ const { _method } = req . body ;
312+ if (
313+ typeof _method !== 'string' &&
314+ ! [ 'PUT' , 'DELETE' ] . includes ( _method )
315+ ) {
316+ throw new Error ( `method override of ${ _method } is not valid` ) ;
317+ }
318+
319+ return _method ;
320+ } )
321+ ) ;
322+
311323 // ajax request detection (sets `ctx.state.xhr` boolean)
312324 app . use ( isajax ( ) ) ;
313325
Original file line number Diff line number Diff line change @@ -18,3 +18,27 @@ test('allows custom routes', async t => {
1818 t . is ( res . status , 200 ) ;
1919 t . is ( res . body . ok , 'ok' ) ;
2020} ) ;
21+
22+ test ( 'allows method override' , async t => {
23+ const router = new Router ( ) ;
24+
25+ router . post ( '/' , ctx => {
26+ ctx . body = { method : 'post' } ;
27+ } ) ;
28+
29+ router . put ( '/' , ctx => {
30+ ctx . body = { method : 'put' } ;
31+ } ) ;
32+
33+ const web = new Web ( {
34+ routes : router . routes ( )
35+ } ) ;
36+
37+ const res = await request ( web . server )
38+ . post ( '/' )
39+ . send ( { _method : 'PUT' } )
40+ . set ( 'Accept' , 'application/json' ) ;
41+ t . is ( res . status , 200 ) ;
42+ t . is ( res . body . method , 'put' ) ;
43+ t . is ( res . request . method , 'POST' ) ;
44+ } ) ;
You can’t perform that action at this time.
0 commit comments