2015-04-29 49 views
0

我正在嘗試使用聚合物核心-ajax向服務器runnung golang發出POST請求。經過大量的搜索(因爲我是這個新東西)我結束了以下代碼。此外,GET請求正在完善。 POST參數我不明白如何通過使用core-ajax。然而使用polymer-ajax發送golang服務器的請求?

<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即

curl -i -H 'Content-Type: application/json' -d '{"Name":"Batman",  
    "Email":"[email protected]"}' http://so.me.ip.ad:8080/register 

它的作品,因爲它應該做一個POST請求,並返回

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": "[email protected]", 
    "createdAt": "2015-04-29T05:40:15.073491143Z" 
} 

另外,我有一個CORS中間件集up on server ie

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, 
}) 

我在做什麼錯?任何反饋都會有很大的幫助!謝謝^^

編輯:這裏是一些更多的信息,如果它可以幫助.. screenshot

+0

瀏覽器通常也發送類似「用戶代理」和「引薦」和這些標頭不列爲你的CORS允許頭middelware - 也許這就是問題? – ain

+0

@ain我添加了「User-Agent」和「Referer」作爲AllowedHeaders,但仍然得到500的迴應:( –

+0

你使用什麼軟件包?嘗試轉儲(在Go服務器中)完整的請求(例如:所有Headers和內容)來檢查您的curl請求和您的聚合請求之間有什麼不同 – LeGEC

回答

2

我覺得CORS是一個紅色的鯡魚。問題可能是你發送的是數據表單編碼,而不是json。我發現一個來自similar problem的用戶的錯誤。

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?請參閱this answer

從聚合物documentation

體:可選生體內容發​​送方法時=== 「POST」。

例子:

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

謝謝,工作!我必須工作儘管如此(將我的聚合物代碼移到同一個域中) –