使用 Express 的外部 API 调用

External API Call Using Express

我正在尝试使用 Express 和 Request 调用大学成绩单 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
            }
        });
    })
};