我正在尝试在Jquery中进行ajax调用,但响应却空了。但是,当我尝试通过卷曲做同样的事情时,我就成功了。这是我的JS,
time = new Date($.now());
requestJSON = '{"Method":"GET","AppName":"Proline","ServiceURL":"http://localhost:8081/api/services/tags/","Properties":null,"Object":"","Timestamp":"'+time+'"}'
$.ajax({
type: "GET",
url: "http://localhost:8081/api/services/tags/",
// The key needs to match your method's input parameter (case-sensitive).
data: requestJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
我也尝试过
dataType: "jsonp"
,但是没有运气。curl命令在这里,
curl --data '{"Method":"GET","AppName":"Proline","ServiceURL":"http://localhost:8081/api/services/tags/","Properties":null,"Object":"","Timestamp":"2016:03:27 00:08:11"}'
-X GET http://localhost:8081/api/services/tags/
我在golang中有服务器代码。我已经将标题设置为
Access-Control-Allow-Headers:*
。这是我的服务器处理程序。 func tagsHandler(w http.ResponseWriter, r *http.Request, extra []string) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"*")
}
// Stop here if its Preflighted OPTIONS request
if r.Method == "OPTIONS" {
return
}
var response []byte
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("FATAL IO reader issue %s ", err.Error())
}
log.Printf("Body : %s ", string(body))
method := r.Method
log.Printf("tagsHandler() :: service method %s ", method)
if method == HTTP_VERB_POST {
response = tagslogic.PostTag(body)
} else if method == HTTP_VERB_GET {
response = tagslogic.GetTags(body)
} else if method == HTTP_VERB_PUT {
response = tagslogic.PutTag(body)
} else if method == HTTP_VERB_DEL {
response = tagslogic.DelTag(body)
}
w.Write(response)
}
具体来说,我正在服务器端获取空的请求正文。
有人可以帮我吗?
最佳答案
您的数据已在console.log中进行了字符串化
time = new Date($.now());
requestJSON = '{"Method":"GET","AppName":"Proline","ServiceURL":"http://localhost:8081/api/services/tags/","Properties":null,"Object":"","Timestamp":"'+time+'"}'
$.ajax({
type: "GET",
url: "http://localhost:8081/api/services/tags/",
data:JSON.stringify(requestJSON),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});