【问题标题】:External API Call Using Express使用 Express 的外部 API 调用
【发布时间】:2018-03-24 22:31:21
【问题描述】:

我正在尝试使用 Express 和 Request 调用 College Score Card API。当我搜索特定学校时,我会收到几所学校的结果,但不是我搜索的学校。这是我的代码的一部分:

var fields = '_fields=school.name,2013.aid.median_debt.completers.overall,2013.repayment.1_yr_repayment.completers,2013.earnings.10_yrs_after_entry.working_not_enrolled.mean_earnings&page=100';

var requestUrl = 'https://api.data.gov/ed/collegescorecard/v1/schools.json?api_key=' + apiKey + '&' + fields;



module.exports = function(app) {
    app.get('/school', function(req, res, next) {
        request(requestUrl, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var json = JSON.parse(body);
                console.log(json); 
            } else {
                console.log("There was an error: ") + response.statusCode;
                console.log(body);
            }
        });
    })
};

HTML:

<form action="/school" method="GET"> 
    <input type="text" class="form-control" name="school_name" value="" id="enter_text"> 
    <button type="submit" class="btn btn-primary" id="text-enter- button">Submit</button> 
</form>

【问题讨论】:

  • html:
  • 使用“编辑”链接将表单代码添加到您的问题并修复了您的格式。请在此处了解如何正确格式化您的代码以使其易于阅读。
  • 什么是requestUrl,它来自哪里?现在,您似乎根本没有在请求中使用表单值,而且您得到的结果似乎完全取决于 requestUrl 是什么。所以,基本上你没有向我们展示代码中最重要的部分。
  • 感谢您的帮助。我是编码新手,这是我第一次提出问题。
  • 学校名称应该如何并入requestUrl?我可以帮助您从表单到 URL 获取它,但我需要知道它在 URL 中应该是什么样子。

标签: api express require


【解决方案1】:

您需要将学校名称合并到 URL 中。从您为method=GET 设置的表单中,名称将出现在req.query.school_name 中。因此,您不只是将请求发送到requestUrl,而是将其发送到:

requestUrl + "&school_name=" + req.query.school_name

这会将其添加到 URL 的末尾:

&school_name=Pepperdine

或者,放入你的代码,它看起来像这样:

module.exports = function(app) {
    app.get('/school', function(req, res, next) {
        request(requestUrl + "&school_name=" + req.query.school_name, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var json = JSON.parse(body);
                console.log(json); 
                res.send(...);    // send some response here
            } else {
                console.log("There was an error: ") + response.statusCode;
                console.log(body);
                res.send(...)     // send some response here
            }
        });
    })
};

【讨论】:

  • 我试过这个,我收到一条消息说“等待本地主机...”,但没有任何反应。
  • @user8767190 - 你真的填写了res.send() 来返回一些内容吗?您必须发送对请求的响应,否则浏览器只会一直等待(最终超时)。您在服务器上的console.log() 语句显示结果了吗?
  • 现在可以使用了。我需要使用 school.name。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-01-11
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多