我正在嘗試使用聚合物核心 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":"[email protected]"}' http://so.me.ip.ad:8080/register它可以正常工作并返回HTTP/1.1 200 OKContent-Type: application/jsonX-Powered-By: go-json-restDate: Wed, 29 Apr 2015 05:40:15 GMTContent-Length: 117{ "id": 3, "name": "Batman", "email": "[email protected]", "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,})我究竟做錯了什么?任何反饋都會有很大幫助!謝謝^.^
1 回答

GCT1015
TA貢獻1827條經驗 獲得超4個贊
我認為 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? 看到這個答案。
從聚合物文件:
body: 可選的原始正文內容,當 method === "POST" 時發送。
例子:
<core-ajax method="POST" auto url="http://somesite.com"
body='{"foo":1, "bar":2}'>
</core-ajax>
- 1 回答
- 0 關注
- 165 瀏覽
添加回答
舉報
0/150
提交
取消