2017-02-21 1 views
1

Express/JSに新しくなったので、これは明らかに不可能な場合には私を許してください。今私はGoogle APIを政府職員のリストを返し、それを使用可能なJSONに掃除する1つのエンドポイントを持っています。Express.js - 既存の内部/ローカルエンドポイントを持つ新しいエンドポイントを構築する

app.get('/api/officials/:zip', (req, res) => { 
    var request = require('request'); 
    request("https://www.googleapis.com/civicinfo/v2/representatives?key=" + process.env.GOOGLE_API_KEY + "&address=" + req.params.zip, function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    // body returns a string so make it onto a JSON object 
    cleanData = (tons of clean up statements); 
    res.send(cleanData); 
    } 
    }) 
}); 

次は、私は上記の結果を返しますが、正式の名前に基づいて特定のエントリにそれを制限する別のエンドポイントを持っています。

app.get('/api/officials/:zip?name=:name', (req, res) => { 
    var request = require('request'); 
    request('/api/officials/' + req.params.zip, function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
     official = _.find(body, {'name': req.query.name}); 
     res.send(official); 
    } 
    }) 
}); 

私はこれをいくつかの方法で試して、2番目のエンドポイントでError: Not Foundを取得しました。

任意の助けもいただければ幸いです。

+0

'console.log'あなたのエンドポイントからの' error'は、完全なエラーの説明は何ですか? –

答えて

1

2番目のAPIエンドポイントのURLが間違っています。

GET /api/officials/:zip?name=:name

URLのクエリは、URLパラメータとは異なる方法で処理されています。 :zipまたは:nameを使用すると、このエンドポイントには2つのreq.paramsがあると言います。

ただし、パラメータの代わりにURLクエリとしてnameを取得することを試みています。

代わりにこれを試してみてください:

GET /api/officials/:zip

URLクエリがexpressによって自動的に処理されます。


あなたの場合、両方の状況を同じAPIエンドポイントで処理できます。ここに私がそれをする方法があります:

app.get('/api/officials/:zip', function(req, res, next) { 

    var request = require('request'); 

    request("https://www.googleapis.com/civicinfo/v2/representatives?key=" + process.env.GOOGLE_API_KEY + "&address=" + req.params.zip, function(error, response, body) { 

    if (!error && response.statusCode == 200) { 

     // body returns a string so make it onto a JSON object 
     cleanData = "tons of clean up statements"; // do your processing 

     if (req.query.name) { // checking if there is a 'name' variable in the req.query object 
     // handling your 2nd API endpoint 

     official = _.find(cleanData, { 'name': req.query.name }); 

     res.send(official); 
     } else { // if no 'name' variable is there in the req.query object just send the clean data 
     // handling your 1st API endpoint 

     res.send(cleanData); 
     } 
    } 
    }); 
}); 
+0

これは非常に役に立ちました。ありがとうございました!今までクエリーは明らかに不明でした。 –

関連する問題