使用Express,Node.JS和Require模块进行外部API调用 [英] External API Calls With Express, Node.JS and Require Module

查看:170
本文介绍了使用Express,Node.JS和Require模块进行外部API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的路线如下:

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)
      }
    }
  });
});

module.exports = router;

我正在尝试对Giant Bomb API进行API调用,以获取有关魔兽世界的所有数据.

I'm trying to make an API call to the Giant Bomb API to bring back whatever data it has about World of Warcraft.

问题是,路线刚刚加载;它什么也没做,也没有超时,只是连续加载.

The problem is, the route just loads; it doesn't do anything or it doesn't time out, it's just continuous loading.

我不知道我在做什么错,但是话又说回来……我也不知道什么是对的.我在尝试学习.

I don't know what I'm doing wrong, but that being said... I don't know what's right either. I'm trying to learn as I go along.

任何帮助都会很棒.

谢谢

推荐答案

您需要获取从request()获得的数据,并将其作为对原始Web服务器请求的响应发送回去.由于您从未发送过任何对原始请求的响应,因此它一直在加载,因此浏览器只是坐在那里等待响应返回,最终它将超时.

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.

由于request()支持流,因此您可以像这样简单地使用.pipe()将数据作为响应发送回去:

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;

这会将.pipe() request()结果.pipe()放入res对象,它将成为对原始http请求的响应.

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

此处的相关答案: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆