2016-11-30 46 views
1

我試圖使用用戶輸入的數據來使用節點對外部API進行api調用。我已成功地從服務器進行調用,並將它們返回到角度。但是我需要從角度向服務器發送一個變量,讓它進行調用,然後將響應返回給我的視圖。我是新來的節點,所以我很抱歉,如果這已經回答了某個地方。我環顧四周,什麼都沒發現。使用angular中的數據在節點express中創建外部api調用

我的HTML

<md-input-container class="md-block" flex-gt-sm> 
    <label>Player 1</label> 
    <input ng-model="player1.username"> 
</md-input-container> 
<md-button ng-click="comparePlayers(player1, player2)">COMPARE!</md-button> 

我的控制器功能

$scope.comparePlayers = function(player1) { 
    Nerd.getPlayer(player1) 
} 

我的 '書呆子' 服務

smiteStats.factory('Nerd', ['$http', function($http) { 
    return { 
      getPlayer: function(playerName) { 
      $http.post('/api/getPlayer', playerName).success(function(data) { 
       console.log("sent to server"); //does not run 
      }) 
     } 
}]); 

個我的快速通道

app.post('/api/getPlayer', GetPlayer.apiGetPlayer); 

我的節點模塊,使API調用

module.exports = { 
    apiGetPlayer: function(error, res, player) { 
     console.log(player); //this returns "[Function: next_layer] in my cmd 
    } 
} 

回答

1

要使用$ HTTP的POST發送參數:

$http({ 
    url: host + '/api/getPlayer', 
    method: "POST", 
    data: { 'fruit1' : "Apple"} 
}) 
.then(function(response) { 
     // success 
}, 
function(response) { // optional 
     // failed 
}); 

要獲取POST參數,您將需要ExpressJS body-parser包。這將允許您從POST中獲取信息。

Read more

+0

這個工作,現在我可以安慰從我的服務器上route.js記錄它,但我怎麼能傳遞req.body到節點模塊? –