lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.43k stars 174 forks source link

How implement Method Override? #183

Closed axmad386 closed 2 years ago

axmad386 commented 2 years ago

Hi, how to override polka method? This is useful for method spoof like this https://laravel.com/docs/9.x/routing#form-method-spoofing. I tried to implement this behavior on polka but not works as expected.

For example I have route

polka().put("/user/:id", (req)=>{
...
})

I want to to access this route via form using POST method and include body: _method = "PUT". I try to use express middleware method-override before declaring polka routes. This middleware override successfully the req.method value. But polka PUT router not triggered. It's still routed to POST. Is I missing something here?

axmad386 commented 2 years ago

@lukeed just want to confirm. Should I override req.method just before this line excecuted? https://github.com/lukeed/polka/blob/2ce10df97921126ffcc43e23aa14af18f93f49e1/packages/polka/index.js#L73 Is this the only way?

axmad386 commented 2 years ago

Hello @lukeed. I ended up to override polka parse to support method override. For others that looking this issue, this is my working code

const originalParser = polka.parse;
polka.parse = (req) => {
      const parsedReq = originalParser(req);

      // just return parsed request if method is get
      if (req.method?.toLocaleLowerCase() == "get") return parsedReq;

      // handle method override if provided by client.
      if (parsedReq.query?._method) {
        req.method = (parsedReq.query._method as string).toUpperCase();
      }
      return parsedReq;
};