2016-07-27 17 views
1

我正尝试在Node.js应用程序中对Yelp进行API调用。我从这里看到我应该使用此代码才能使用Yelp API:https://arian.io/how-to-use-yelps-api-with-node/。我在我的app.js文件中使用了该代码。现在为了它在浏览器上显示结果,我知道我必须将控制器连接到视图(在我的情况下是index.html),并使用$ scope绑定这两个文件。但我也必须以某种方式将控制器连接到app.js.我跟在arian.io上的教程说:如何在Node.js/Express/Angular应用程序中对Yelp进行外部API调用

现在,如果您调用函数request_yelp(params,callback),它将使用这些参数callback(error,response,body)调用回调函数。 就是这样,现在你已经准备好充分利用Yelp的API了。

但如何或在哪里我调用该函数?我假设我会在我的控制器中执行此操作,但我已经尝试过,但没有奏效。总结我的问题,如果API调用是正确的并且它应该在哪里,那么我的下一步就是将它与我​​的控制器连接,一旦这两者连接,我必须将html绑定到apiController.js与$范围为了使我的数据结果显示在浏览器中。我知道我错过了很多东西,但我认为我有正确的想法。

任何帮助,欢迎。谢谢!

My app's tree 
 

 
>.git 
 
>bower_components 
 
>client 
 
    >controllers 
 
     -apiControllers (My one and only controller) 
 
    >css 
 
    >views    (This is empty) 
 
    app.js 
 
    index.html (This is my one and only page/ my app is a one page app) 
 
    package.json 
 
>models 
 
>node_modules 
 
app.js (This is where I am trying to make the API call) 
 

 

 
<-- ================================================== --> 
 

 
//This is my app.js file 
 

 

 
    //Call packages needed 
 
    var express = require('express'); 
 
    var app = express();     
 
    var bodyParser = require('body-parser'); 
 
    var mongoose = require('mongoose'); 
 
    var dotenv = require('dotenv').config(); 
 
    var oauthSignature = require('oauth-signature'); 
 
    var n = require('nonce')(); 
 
    var request = require('request'); 
 
    var qs = require('querystring'); 
 
    var _ = require('lodash'); 
 

 
    // Function for yelp call 
 
    var request_yelp = function(set_parameters, callback) { 
 

 
     var httpMethod = 'GET'; 
 

 
     var url = 'http://api.yelp.com/v2/search'; 
 

 
     var default_parameters = { 
 
     location: 'New+York', 
 
     sort: '2' 
 
     }; 
 

 
     var required_parameters = { 
 
     oauth_consumer_key : process.env.yelp_consumer_key, 
 
     oauth_token : process.env.yelp_token, 
 
     oauth_nonce : n(), 
 
     oauth_timestamp : n().toString().substr(0,10), 
 
     oauth_signature_method : 'HMAC-SHA1', 
 
     oauth_version : '1.0' 
 
     }; 
 

 
     var parameters = _.assign(default_parameters, set_parameters, required_parameters); 
 

 
     var consumerSecret = process.env.yelp_consumer_secret; 
 
     var tokenSecret = process.env.yelp_token_secret; 
 

 
     var signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret, { encodeSignature: false}); 
 

 
     parameters.oauth_signature = signature; 
 

 
     var paramURL = qs.stringify(parameters); 
 

 
     var apiURL = url+'?'+paramURL; 
 

 
     request(apiURL, function(error, response, body){ 
 
     return callback(error, response, body); 
 
     }); 
 

 
    }; 
 

 
    app.use(express.static(__dirname+'/client')); 
 

 
    app.get('/', function request_yelp(params, callback){ 
 
     res.send('This is the main page'); 
 
    }); 
 

 
    app.listen(3000); 
 
    console.log('Running on port 3000'); 
 

 

 
<-- ================================================== --> 
 
<!-- This is index.html. Here I would like to display my YELP responses. I am using Bootstrap 
 

 
<div class="container-fluid"> 
 
    <div class="row-fluid"> 
 
     <!-- <div class="container-fluid"> --> 
 
     <!-- <div class="jumbotron"> --> 
 
        <div class="row-fluid"> 
 
         <!-- <div ng-controller="MainCtrl"> --> 
 
          <p><date-input name="info.name" message="info.message"></date-input></p> 
 
       <div data-ng-repeat="business in businesses"> 
 
          <!-- <div class="col-lg-offset-1"> --> 
 
          <div class="col-lg-2 col-lg-offset-2 col-md-3 col-sm-2 col-xs-6 text-center"> 
 
            <p>Breakfast</p> 
 
           <div class="thumbnail"> 
 
            <img class="img-responsive img-circle" src="{{business.image_url}}"> 
 
            <h5>{{business.name}}</h5> 
 
            <h5>{{business.rating}}</h5> 
 
            <h5>"{{business.snippet_text}}"</h5> 
 
            <h5>{{business.categories[0]}}</h5> 
 
            <p><a class="btn btn-link btn-sm" href="{{business.url}}">View details &raquo;</a></p> 
 
            <p><a class="btn btn-xs btn-info" id="breakfast" role="button" onClick="refreshPage()">I don't like this one!</a></p> 
 
           </div><!-- End thumbnail --> 
 
          </div><!-- End col-md-4 --> 
 

 

 
<-- ================================================== --> 
 

 
// Finally this is my apiController.js. What code do I need here to connect the API call to my view? 
 

 
var myApp = angular.module('myApp', []); 
 

 
myApp.controller('MainCtrl', ['$scope'function($scope) { 
 
    $scope.total = []; 
 
    $scope.businesses = []; 
 

 
}])

回答

0

首先,我要做出一系列的意见之前,我试图回答你的问题。

app.js文件似乎做得太多。我知道你想制作一个单页的应用程序,但是一些结构可能会有所帮助。如果你让你的app.js文件处理应用程序引导逻辑,那将会很好。这是连接到数据库和射击您的Express服务器

var express = require('express'), 
    routes = require('./routes'), 
    app = express(); 

    /*load application middleware here */ 

    /*Connect to databse, if needed */ 

    /* load routes */ 
    routes(app) 

    /*Fire up the server */ 
    app.listen(3000, function(){ 
     console.log('Server listening on port 3000'); 
    }); 

你需要有一个控制器,处理任何外部API的拨打电话,还可以节省您的数据库。控制器文件是您在某种方法中进行API调用的地方。

module.exports = { 
     makeApiCall: function(req, res) { 
      /* return response after call */ 
     } 
    } 

后您设置控制器,你需要的路线上暴露的功能,像这样:

var controller = require('./controller'); 
    module.exports = function(){ 
     app.get('routes/segment', controller.method); 
     /* load more routes if any */ 
    } 

然后在角度,你需要创建一个服务,使一个调用在您的后端路由段并返回响应。您会将服务注入到您的控制器中,并使控制器在您的页面上可用,但对您来说更方便。

Ex。 Filename.service.js

angular.module('MyModule') 
    .service('ServiceName', ['$http', 'anotherDependency', ServiceFunction]); 

function serviceFunction ($http, anotherDependency) { 
    return { 
     $http.get('route/segment').then(function (res) { 
      /*return response, promises are better */ 
     }, function (err) { 
      /* Return error if any */ 
     }); 
    } 
} 

FileName.controller.js

angular.module('MyModule') 
    .controller('MyController', ['ServiceName', ControllerFunction]); 

    function controllerFunction(ServiceName){ 
     var vm = this; 
     ServiceName.makeCall().then(function (res){ 
     //set result on vm to make it accessible on your view. 
     }).catch(function (err)) { 
     //report error if any 
     } 
    } 

然后在您看来,您可以使用Controller as语法加载控制器。

+1

谢谢Daniel,这对我有很大的帮助。 – ksan

相关问题