J. Doe J. Doe - 1 year ago 108
Node.js Question

Bind ServerResponse object to function

I'm pretty new to ES itself and wondering about why I can't properly bind ServerResponse object to a function.
I've got a pretty simple server that utilizes OAuth protocol:

let saveToken = (response) =>
{
console.log('\n')
console.log(this.constructor) // NOT OK [Function: Object]

this.writeHead(200,
{
'Set-Cookie': `${ACCES_TOKEN_COOKIE}=${JSON.parse(response.body).access_token}`
})

this.send(body)
}

let requestToken = (code) =>
{
console.log('\n')
console.log(this.constructor) // NOT OK [Function: Object]

unirest.post(OAUTH_ACCESS_URL)
.send({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code: code,
redirect_uri: REDIRECT_URI
})
.end(saveToken.bind(this))

}

let requestsHandler = (request, response) =>
{
console.log('\n')
console.log(response.constructor) // OK { [Function: ServerResponse] }

let QUERY = url.parse(request.url, true).query;

if ('code' in QUERY)
{
requestToken.bind(response)(QUERY.code)
} else
{

fs.readFile(INDEX_PAGE_PATH,
'utf8',
(err, contents) =>
{
response.send(contents)
})

}

}

let app = express()
app.get('/', requestsHandler)

app.listen(PORT,
() =>
{
console.log(`Server listening on :${PORT}`)
})


Here I'm trying to bind
ServerResponse
object (
response
) to
requestToken
within
requestsHandler
but it seems like I'm doing something wrong because
this
becomes a plain
Object
as soon as
requestToken
is being called.
What am I doing wrong?

Answer Source

I figured out that request module utilized by unirest binds other object to the callback within it's routines

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download