繁体   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