req.uest
is an Express middleware that allows you, from a given route, to request another route.
Features are:
req
cookies are passed along to subsequent req.uest
sreq.uest
s responses are forwarded to initial res
req.session
stay in sync between requestsIt allows you to decouple your app's routes from your API's ones. IOW, your app routes can now consume your API as any client.
$ npm i uest
// app.js
const uest = require('uest')
app.use(uest())
req.uest(options, (er, resp, body) => {})
options
-- are the same as request/request, with defaults to json: true
and baseUrl
to the same as your Express server.resp
-- the response object, see: http.IncomingMessage
resp.body
holds the JSON response dataser
-- when an error occurs or resp.statusCode >= 400
, see: http.ClientRequest
er.status
holds the response statusCode, for example: 404
or 409
...It also supports await
:
const [resp, body] = await req.uest(options)
// Mount our API router
app.use('/api', require('./routers/api'));
//
// App routing
//
app.post('/login', (req, res, next) => {
const {email, password} = req.body
//
// Our subsequent request to `POST /api/sessions` route
//
req.uest({
method: 'POST',
url: '/api/sessions',
body: {email, password}
}, (er, resp, body) => {
if (er) {
// Deal with specific "Forbidden" error
if (er.status === 403) {
return res.render('login', {error: "Wrong login/password"})
}
return next(er); // for any other error
}
console.log('User-session created for', body.user)
// `req.session` is up-to-date
console.log(`Welcome back ${req.session.user.firstname}!`
res.redirect('/profile')
})
});