简体   繁体   中英

Node.js `request.get`: store body in variable

I'm new to Node.js, and so sorry for what is probably a dumb question…

Here's my code:

#!/usr/bin/env coffee --bare

#   3rd party
request  = require('request')
request.defaults({'encoding': 'utf8'})

module.exports.fetchDepartments = fetchDepartments

fetchDepartments = (url) ->
    _body = ''

    getHandler = (error, response, body) -> 
        util.debug "HTTP response code: #{response.statusCode}"

        if error
            util.error error
        else    
            _body = body

    request.get(url, getHandler)
    _body

console.log fetchDepartments('https://ntst.umd.edu/soc/')

The console is printing the call to util.debug() , but it seems that _body remains an empty string.

…How can I store the HTML from the HTTP response?!?

You seem to be returning the _body before the request is completed.

The request is not synchronous, so you'll almost certainly want to define a callback instead. In plain JavaScript, that would be:

fetchDepartments('https://ntst.umd.edu/soc', function (err, body) {
    console.log(body);
});

What it's currently doing is:

  1. Initialise _body to ''
  2. Create (but not execute!) getHandler
  3. Start the request
  4. Return the (still-empty) _body
  5. Log the (empty) _body
  6. Later: the request completes, calling getHandler
  7. getHandler() updates _body

What you need to do is to make fetchDepartments accept callback function, so that whatever code processes _body can wait until the request is complete.

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