2017-03-08 129 views
-3

點擊index.html代碼中顯示的按鈕會給我一個錯誤信息「$ http.post」(網頁提示'Error!',所以我無法保存新的JSON文件,因爲我不能讓過去的這個電話。HTTP Post不能正常工作

我在做什麼錯?

的index.html

<td><input id="clickMe" type="button" value="clickme" ng-click="doPost()" /></td> 

app.js

... 
$scope.doPost = function() 
         { 
          $http.post('/resource', {param1: 1, param2: 2} 
          ).success(function() 
           { 
            alert("OK!"); 
           }) 
           .error(function() 
           { 
            alert("Error!"); 
           }); 
         } 
... 

個index.js(服務器)

var fs = require('fs'); //File system module 
server.post('/resource', function(request, response) 
{ 
     //Every HTTP post to baseUrl/resource will end up here 
     console.info('Updated myJSON.json'); 
     fs.writeFile('myJSON.json', request.body, function(err) 
     { 
      if(err) 
      { 
       console.error(err); 
       return response.status(500).json(err); //Let the client know something went wrong 
      } 
       console.info('Updated myJSON.json'); 
       response.send(); //Let the client know everything's good. 
     }); 
}); 
+0

有什麼錯誤?服務器對服務器的要求是什麼?服務器的迴應是什麼? – David

+0

錯誤是我得到警報:錯誤! 當我使用HTTP.post 沒有成功,它應該提醒我「OK!」。 –

+1

是的,由於您編寫了代碼來顯示警報,因此您會收到警報。然而,錯誤信息會導致''Error!「'無用。那麼你的代碼忽略的*實際錯誤*是什麼?我懷疑一個函數參數正在傳遞給那個'.error()'回調函數,那個參數是什麼?在瀏覽器的調試工具的網絡選項卡中,服務器的實際響應是什麼? – David

回答

1

使用則$ HTTP之類的函數

$http.post('/resource', {param1: 1, param2: 2}).then(function successCallback(response) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }, function errorCallback(response) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 
+0

試過這個,什麼都沒有。 –

+0

然後問題與您的nodejs api,$ http工作是這樣的,與$ http沒有問題 – Gaurav