2016-07-26 145 views
-1

我是angularjs中的新成員。我試圖通過$ http post發佈一些數據到服務器。我的代碼可能會到達服務器,但數據不會傳遞。我使用golang作爲後端。我在這裏犯了什麼錯誤?

completeCampaign.controller('campaignCtrl', ['$scope', '$http', function(scope, http) { 
    var Msg = "hai"; 
    http.post("/server_url",Msg).then(function(response) { 
     console.log(response); 
    }); 
}]); 

Go代碼:

func (c *CarController) TestFunction() { 
    msg := c.GetString("Msg") 
    fmt.Println("Message is: ", msg) 
} 

輸出:

Message is: 
+0

你得到的「消息」,而不是在服務器的身體可能 – Alessio

回答

2

使用$符號:

$http.post("/server_url",Msg).then(function(response) { 
    console.log(response); 
}); 
+0

沒有..現在它甚至沒有到達服務器。我已經將'$ scope'定義爲範圍..'$ scope','$ http',函數(scope,http) –

1

「角$ HTTP POST接受JSON對象作爲POST參數,而你只是發送一個字符串「(謝謝@ Kausik E vani)

此外,你有一個錯字http,嘗試更新你的代碼。

completeCampaign.controller('campaignCtrl', ['$scope', '$http', function($scope, $http) { 
    var data = {msg: "hello"}; 

    $http.post("/server_url", data).then(function(response) { 
     console.log(response); 
    }); 
}]); 
+0

仍然不能正常工作 –

+0

您能確保您的Go代碼正確嗎? 。 http://stackoverflow.com/questions/15672556/handling-json-post-request-in-go – Alejandro

1

@AlejandroBáezArcila的答案當然是絕對正確的。對不起,作爲一個迂腐,但它不完全是一個錯字。而且OP最好能知道爲什麼他的POST不起作用。 Angular $ http post接受JSON對象作爲POST參數,而你只是發送一個字符串。 就像@AlejandroBáezArcila建議的一樣,將它發送爲var data = {msg: "hai"};,並在服務器上只訪問「msg」鍵。