External API Calls With Express, Node.JS and Require Module

前端 未结 2 1997
既然无缘
既然无缘 2020-12-08 01:17

I have a route as followed:

var express = require(\'express\');
var router = express.Router();
var request = require(\'request\');

router.get(\'/\', functio         


        
相关标签:
2条回答
  • 2020-12-08 02:11

    Per every route in Express, it is necessary to send a response (partial or complete) or call next, or do both. Your route handler does neither. Try

    var express = require('express');
    var router = express.Router();
    var request = require('request');
    
    router.get('/', function(req, res, next) {
      request({
        uri: 'http://www.giantbomb.com/api/search',
        qs: {
          api_key: '123456',
          query: 'World of Warcraft: Legion'
        },
        function(error, response, body) {
          if (!error && response.statusCode === 200) {
            console.log(body);
            res.json(body);
          } else {
            res.json(error);
          }
        }
      });
    });
    
    module.exports = router;
    

    and see what data this route handler responds with.

    0 讨论(0)
  • 2020-12-08 02:13

    You need to take the data you get from request() and send it back as the response to the original web server request. It was just continuously loading because you never sent any sort of response to the original request, thus the browser was just sitting there waiting for a response to come back and eventually, it will time out.

    Since request() supports streams, you can send back the data as the response very simply using .pipe() like this:

    var express = require('express');
    var router = express.Router();
    var request = require('request');
    
    router.get('/', function(req, res, next) {
      request({
        uri: 'http://www.giantbomb.com/api/search',
        qs: {
          api_key: '123456',
          query: 'World of Warcraft: Legion'
        }
      }).pipe(res);
    });
    
    module.exports = router;
    

    This will .pipe() the request() result into the res object and it will become the response to the original http request.

    Related answer here: How to proxy request back as response

    0 讨论(0)
提交回复
热议问题