Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A callback is just a word to describe a function that we pass to some other code for that other code to invoke.</p> <p>In your example, <code>onRequest</code> is a callback function that gets passed to <code>createServer</code> to be invoked whenever a request is received.</p> <p>I think the issue you're having is that you're expecting <code>expand()</code> to have access to all the same variables/parameters that the <code>onRequest</code> function has access to. This isn't the case. </p> <p>You need pass the <code>response</code> object to <code>expand()</code>. Because the call to <code>expand</code> creates a new callback <code>longURL</code> for the <code>http.get</code> call, it will have access to the <code>response</code> object that you passed in.</p> <pre><code>function expand( resp ) { // receive the original response object, and end the response when ready var short = url.parse('http://t.co/wbDrgquZ'); var options = { host: short.hostname, port: 80, path: short.pathname }; function longURL( response ) { console.log(response.headers.location); resp.end( response.headers.location ); // end the original response } http.get(options, longURL); } function start() { function onRequest(request, response) { console.log("Request received."); response.writeHead(200, { "Content-Type": "text/plain" }); response.write("Hello World"); expand( response ); // pass this response object to expand } http.createServer(onRequest).listen(8888); console.log("Server has started."); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload