Node.JS Wait for callback of REST Service that makes HTTP request

前端 未结 3 1808
故里飘歌
故里飘歌 2020-12-23 02:42

I am using express module to make a Restful API within Node.JS. In my service I am making additional http requests to outside Endpoints(server side) and I need to return the

3条回答
  •  萌比男神i
    2020-12-23 03:15

    Node.js is all about callbacks. Unless the API call is synchronous (rare and shouldn't be done) you never return values from those calls, but callback with the result from within the callback method, or call the express method res.send

    A great library for invoking web requests is request.js

    Let's take the really simple example of calling google. Using res.send, your express.js code could look like:

    var request = require('request');
    app.get('/callGoogle', function(req, res){
      request('http://www.google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          // from within the callback, write data to response, essentially returning it.
          res.send(body);
        }
      })
    });
    

    Alternatively, you can pass a callback to the method that invokes the web request, and invoke that callback from within that method:

    app.get('/callGoogle', function(req, res){
      invokeAndProcessGoogleResponse(function(err, result){
        if(err){
          res.send(500, { error: 'something blew up' });
        } else {
          res.send(result);
        }
      });
    });
    
    var invokeAndProcessGoogleResponse = function(callback){
      request('http://www.google.com', function (error, response, body) {
    
        if (!error && response.statusCode == 200) {
          status = "succeeded";
          callback(null, {status : status});
        } else {
          callback(error);
        }
      })
    }
    

提交回复
热议问题