2015-04-29 46 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

谢谢,工作!我必须工作尽管如此(将我的聚合物代码移到同一个域中) –