簡體   English   中英

使用聚合物核心Ajax向Golang服務器發布請求?

[英]Post request to golang server using polymer core-ajax?

我正在嘗試使用聚合物core-ajax向服務器runnung golang發出POST請求。 經過大量搜索(因為我是這個東西的新手),我最終得到了以下代碼。 另外,GET請求也很完美。 POST參數我不明白如何使用core-ajax傳遞。

<polymer-element name="register-user" attributes="url">
    <template>
        <core-ajax id="ajaxSubmit" url="{{url}}" contentType="application/json" handleAs="json" method="post" on-core-response="{{response}}"></core-ajax>
        <style type="text/css">
        </style>
    </template>
    <script>
    Polymer({
        buttonListener: function() {
            var data = '{"Name":"'+ this.name +'", "Email":"'+ this.email +'"}';
            this.$.ajaxSubmit.data = data;
            this.$.ajaxSubmit.go();
            console.log(data);
        },
        response: function(oldValue){
            console.log(this.response);
        }
    });
    </script>
</polymer-element>

上面的代碼返回500 (Internal Server Error)但是當我使用curl發出POST請求時

curl -i -H 'Content-Type: application/json' -d '{"Name":"Batman",    
     "Email":"batman@gmail.com"}' http://so.me.ip.ad:8080/register

它可以正常工作並返回

HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Wed, 29 Apr 2015 05:40:15 GMT
Content-Length: 117

{
  "id": 3,
  "name": "Batman",
  "email": "batman@gmail.com",
  "createdAt": "2015-04-29T05:40:15.073491143Z"
}

另外,我在服務器上設置了CORS中間件,即

api.Use(&rest.CorsMiddleware{
    RejectNonCorsRequests: false,
    OriginValidator: func(origin string, request *rest.Request) bool {
        return origin == "http://0.0.0.0:8000"
    },
    AllowedMethods: []string{"GET", "POST", "PUT"},
    AllowedHeaders: []string{
        "Accept", "Content-Type", "X-Custom-Header", "Origin"},
    AccessControlAllowCredentials: true,
    AccessControlMaxAge:           3600,
})

我究竟做錯了什么? 任何反饋都會有很大幫助! 謝謝^。^

編輯:如果有幫助,這里有更多信息。 屏幕截圖

我認為CORS是紅鯡魚。 問題可能是您發送的是格式編碼的數據,而不是json。 我從一個有類似問題的用戶那里發現了一個錯誤。

HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 04:29:59 GMT
Content-Length: 71

{
  "Error": "invalid character '\\'' looking for beginning of value"
}

也許您應該使用.body而不是.data 看到這個答案

從聚合物文檔中

正文:方法===“ POST”時發送的可選原始正文內容。

例:

<core-ajax method="POST" auto url="http://somesite.com"
    body='{"foo":1, "bar":2}'>
</core-ajax>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM