Calling Express Route internally from inside NodeJS

前端 未结 3 1440
忘了有多久
忘了有多久 2020-12-06 04:18

I have an ExpressJS routing for my API and I want to call it from within NodeJS

var api = require(\'./routes/api\')
app.use(\'/api\', api);

3条回答
  •  温柔的废话
    2020-12-06 04:56

    I've made a dedicated middleware for this : uest.

    Available within req it allows you to req.uest another route (from a given route).

    It forwards original cookies to subsequent requests, and keeps req.session in sync across requests, for ex:

    app.post('/login', async (req, res, next) => {
      const {username, password} = req.body
    
      const {body: session} = await req.uest({
        method: 'POST',
        url: '/api/sessions',
        body: {username, password}
      }).catch(next)
    
      console.log(`Welcome back ${session.user.firstname}!`
    
      res.redirect('/profile')
    })
    

    It supports Promise, await and error-first callback.

    See the README for more details

提交回复
热议问题