lukeed / polka

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

subApps/routes #81

Closed shman2000 closed 5 years ago

shman2000 commented 5 years ago

Hi,

I'm getting 404 after switching from express.

I use this code in index.js:

const app = polka();

/**
* Middlewares
*/
middlewaresConfig(app);

var cors = require('cors');
app.use(cors( { origin:true, credentials: true } ) );

app.use('/api/', [ UserRoutes, UploadRoutes, WorkspaceRoutes, ProjectRoutes, TaskRoutes, NotificationRoutes, 
  GitHubRoutes, StatusTableRoutes, UpgradeRoutes, BitbucketRoutes, SlackRoutes, ApiUserRoutes, GoogleRoutes,
  DropboxRoutes, SettingsRoutes, SyncRoutes, TagsRoutes, AffiliateRoutes, ReminderRoutes, ZapierRoutes ]);

And modules looks like this:

const polka = require('polka');

import * as SyncController from './controller';

const app = polka();

app.post('/sync/doSync', SyncController.doSync);

export default app;

I tried also adding modules one by one:

app.use('/api/', UserRoutes);

without success.

lukeed commented 5 years ago

Hey, about to be by my computer, so will double check in a few minutes, but I think it's because you included trailing slash in your /api/ base

Try making it /api and it looks like it should work

shman2000 commented 5 years ago

Thanks! Trailing slash was the reason.

Polka dropped this:

/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95
        let loop = _ => res.finished || (i < len) && arr[i++](req, res, next);
                                                             ^

TypeError: arr[(i++)] is not a function
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.arr.length.arr.push (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:56:65)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at cors (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:188:7)
    at /Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:224:17
    at originCallback (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:214:15)
    at /Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:219:13
    at optionsCallback (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:199:9)
    at Array.corsMiddleware (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:204:7)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.initialize (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/passport/lib/middleware/initialize.js:53:5)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.logger (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/morgan/index.js:144:5)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.multerMiddleware (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/multer/lib/make-middleware.js:18:41)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)

Looks like a problem with the response. I will check middleware as well. Any ideas?

lukeed commented 5 years ago

You can wrap these lines in a try/catch to get some idea about what is throwing. Looking at the stack, I can't tell yet :/

Polka isn't fully compatible with Express apps (yet), so the initial hand-off may be a little painful

shman2000 commented 5 years ago

I did some debugging, added try catch as you proposed. Checked what is happening with arr[i++].

function jsonParser(req, res, next) {
    if (req._body) {
      debug('body already parsed')
      next()
      return
    }

    req.body = req.body || {}

    // skip requests without bodies
    if (!typeis.hasBody(req)) {
      debug('skip empty body')
      next()
      return
    }

    debug('content-type %j', req.headers['content-type'])

    // determine if request should be parsed
    if (!shouldParse(req)) {
      debug('skip parsing')
      next()
      return
    }

    // assert charset per RFC 7159 sec 8.1
    var charset = getCharset(req) || 'utf-8'
    if (charset.substr(0, 4) !== 'utf-') {
      debug('invalid charset')
      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
        charset: charset,
        type: 'charset.unsupported'
      }))
      return
    }

    // read
    read(req, res, next, parse, debug, {
      encoding: charset,
      inflate: inflate,
      limit: limit,
      verify: verify
    })
  }
Polka error:  TypeError: arr[(i++)] is not a function
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:97:57)

Which is strange, returns a function but throws an error that it's not a function.

It may be also worth to mention that I'm using:

const send = require('@polka/send-type');

And middleware looks like this:

export default app => {
  try {
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(multer({ dest: '../tmp/' }).any());
    app.use(morgan('dev'));
    app.use(passport.initialize());
  } catch(e) {
    console.log("Middleware error", e);
  }

};

I know it's not 100% express compatible. But maybe using this case, we can build an example which will help other people.

lukeed commented 5 years ago

Thanks, can you show me how you're using this block?

export default app => {
  try {
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(multer({ dest: '../tmp/' }).any());
    app.use(morgan('dev'));
    app.use(passport.initialize());
  } catch(e) {
    console.log("Middleware error", e);
  }
};
shman2000 commented 5 years ago

Sure:

const app = polka();

/**
* Middlewares
*/
middlewaresConfig(app);

bdw. If I disable middleware I still get this error:

(r, _, nxt) => (mutate(base, r),nxt())
Polka error:  TypeError: arr[(i++)] is not a function
shman2000 commented 5 years ago

Update:

so this doesn't work:

app.use('/api', UserRoutes)
.use('/api', UploadRoutes)
.use('/api', WorkspaceRoutes)
.use('/api', ProjectRoutes)
.use('/api', TaskRoutes)
.use('/api', NotificationRoutes)
.use('/api', GitHubRoutes)
.use('/api', StatusTableRoutes)
.use('/api', UpgradeRoutes)
.use('/api', BitbucketRoutes)
.use('/api', SlackRoutes)
.use('/api', ApiUserRoutes)
.use('/api', GoogleRoutes)
.use('/api', DropboxRoutes)
.use('/api', SettingsRoutes)
.use('/api', SyncRoutes)
.use('/api', TagsRoutes)
.use('/api', AffiliateRoutes)
.use('/api', ReminderRoutes)
.use('/api', ZapierRoutes)
.use('/ical', IcalRoutes);

this as well doesn't work:

app.use('/api', [ UserRoutes, UploadRoutes, WorkspaceRoutes, ProjectRoutes, TaskRoutes, NotificationRoutes, GitHubRoutes, StatusTableRoutes, UpgradeRoutes, BitbucketRoutes, SlackRoutes, ApiUserRoutes, GoogleRoutes, DropboxRoutes, SettingsRoutes, SyncRoutes, TagsRoutes, AffiliateRoutes, ReminderRoutes, ZapierRoutes ]);

It seems that adding multiple Polka routes to the same path "/api" is a problem. Only last one seems to work.

Any idea how to approach it?

lukeed commented 5 years ago

Oh, hah, just dawned on me. You are assigning an array. The use is variadic so it will cast your multiple apps to an array for you.

app.use('/api', foo, bar, baz, bat)
lukeed commented 5 years ago

The upcoming 1.0 will solve this, preventing the silent error for incorrect usage.

aswathpandiyan commented 4 years ago

Thanks! Trailing slash was the reason.

Polka dropped this:

/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95
      let loop = _ => res.finished || (i < len) && arr[i++](req, res, next);
                                                           ^

TypeError: arr[(i++)] is not a function
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.arr.length.arr.push (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:56:65)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at cors (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:188:7)
    at /Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:224:17
    at originCallback (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:214:15)
    at /Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:219:13
    at optionsCallback (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:199:9)
    at Array.corsMiddleware (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/cors/lib/index.js:204:7)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.initialize (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/passport/lib/middleware/initialize.js:53:5)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.logger (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/morgan/index.js:144:5)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)
    at Array.multerMiddleware (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/multer/lib/make-middleware.js:18:41)
    at loop (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:95:56)
    at next (/Users/kamilkwiecien/Documents/repo/taskeo/backend/node_modules/polka/index.js:94:63)

Looks like a problem with the response. I will check middleware as well. Any ideas?

check your handler name is correct