I need to call a third party API server in NodeJS, as you can see below, I need to use req and resp inside request() method.
Since there are a lot of APIs that I need to use, I don't want to set headers and set response cookies every time I use request().
Is there anything I can do to intercept request()?
router.post('/register', function (req, resp) {
var api = "/user/register"
var data = req.body)
request({
url: api,
method: "POST",
json: true,
headers: {'session_id' : req.cookies.session_id},
body: {
"tel": data.tel, "code": data.code,
"password": data.passwd, "referee": data.recommend
}
}, function (error, response, body) {
resp.cookies('session_id', response.headers['sessionId'])
resp.json(body)
})
})
requestpackage doesn't know nothing aboutexpressand himrequestandresponseobjects, so you can't intercept. But you can create two simple functions which will extract required info fromreqand updateres. Just call these functions in every call ofrequest.