简体   繁体   中英

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?

我发现unirest使用的request模块将其他对象绑定到其例程中的回调

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM