Search code examples
apiexpressrequire

External API Call Using Express


I'm trying to call a College Score Card API using Express and Request. When I search for a specific school, I receive results from several schools, but not the school I searched for. Here is part of my code:

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>

Solution

  • You need to incorporate the school name into the URL. From your form that is set for method=GET, the name will come in req.query.school_name. So, instead of just sending the request to requestUrl, you send it to:

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

    which will add this onto the end of the URL:

    &school_name=Pepperdine
    

    Or, put into your code, it would look like this:

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