使用Express的外部API调用
我试图使用Express和请求调用College Score Card API。当我搜索一所特定的学校时,我收到了几所学校的成绩,但没有收到我搜索的学校的成绩。这里是我的代码部分:使用Express的外部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>
你需要把校名到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
@ user8767190 - 您是否实际填写了'res.send()'来返回一些内容? 您必须发送对请求的响应,或者浏览器只是坐下来等待(最终超时)。你的'console.log()'语句在服务器上显示了结果吗? – jfriend00
现在有效。我需要使用school.name。谢谢你的帮助! – user8767190
HTML: \t \t 提交 – user8767190
添加形式码到您的问题使用“编辑”链接并修复您的格式。请了解如何在此处正确设置代码格式,以便于阅读。 – jfriend00
什么是'requestUrl',它来自哪里?现在,在你的请求中并没有出现你使用表单值的情况,看起来你得到的结果完全取决于requestUrl是什么。所以,基本上你没有向我们展示代码中最重要的部分。 – jfriend00