简体   繁体   English

使用 Express、Node.JS 和 Require 模块进行外部 API 调用

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

I have a route as followed:我有如下路线:

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;

I'm trying to make an API call to the Giant Bomb API to bring back whatever data it has about World of Warcraft.我正在尝试对 Giant Bomb API 进行 API 调用,以带回它拥有的关于魔兽世界的任何数据。

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.我正在努力学习。

Any help would be great.任何帮助都会很棒。

Thanks谢谢

You need to take the data you get from request() and send it back as the response to the original web server request.您需要从request()获取数据并将其作为对原始 Web 服务器请求的响应发送回。 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.由于request()支持流,您可以像这样使用.pipe()非常简单地将数据作为响应发送回。

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.这将.pipe() request()结果放入res对象,并将成为对原始 http 请求的响应。

Related answer here: How to proxy request back as response此处的相关答案: 如何将请求作为响应代理返回


Edit in 2021. The request() library has now been deprecated and is no longer recommended for new code. 2021 年编辑request()库现已弃用,不再推荐用于新代码。 There are many alternatives to choose from.有很多选择可供选择。 My favorite is the got() library.我最喜欢的是got()库。 The above could be accomplished using it like this.上面可以这样使用它来完成。 This also upgrades to use the pipeline() function which is a better version of .pipe() with more complete error handling.这也升级为使用pipeline()函数,它是.pipe()的更好版本,具有更完整的错误处理。

const router = require('express').Router();
const got = require('got');
const { pipeline } = require('stream');

router.get('/', function(req, res) {
  const dataStream = got.stream({
      uri: 'http://www.giantbomb.com/api/search',
      qs: {
        api_key: '123456',
        query: 'World of Warcraft: Legion'
      }
  });
  pipeline(dataStream, res, (err) => {
      if (err) {
          console.log(err);
          res.sendStatus(500);
      }
  });
});

module.exports = router;

Per every route in Express, it is necessary to send a response (partial or complete) or call next , or do both.对于 Express 中的每条路由,都需要发送响应(部分或完整)或调用next ,或者两者都做。 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.并查看此路由处理程序响应的数据。

For Laravel users,对于 Laravel 用户,

First of all install npm i axios package if not.如果没有,首先安装npm i axios包。

var axios = require('axios');

var config = {
    /* Your settings here like Accept / Headers etc. */
}

axios.get('http://local.dev/api/v1/users', config)
.then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
});

Hopefully it will help someone!希望它会帮助别人!

Though the core problem was already stated, the code is incorrect (That's why the second solution didn't work). 虽然核心问题已经陈述,但代码不正确(这就是为什么第二个解决方案不起作用的原因)。 The callback that is supposed to be a second parameter is in fact a part of the object (first parameter). 应该是第二个参数的回调实际上是对象的一部分(第一个参数)。

In 2022 2022年

In node在节点

 const fetch = (...args) => import('node-fetch').then(({default: fetch}) => 
 fetch(...args));

app.get('/checkDobleAPI', async (req, res) => {
try {

const apiResponse = await fetch(
 'https://jsonplaceholder.typicode.com/posts' 
)
const apiResponseJson = await apiResponse.json()

console.log(apiResponseJson)
res.send('Running 🏃')
} catch (err) {
console.log(err)
res.status(500).send('Something went wrong')
}
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM