【发布时间】:2016-03-27 09:53:28
【问题描述】:
我正在尝试在 Jquery 中进行 ajax 调用,但得到的响应是空的。但是当我尝试通过 curl 做同样的事情时,我成功了。这是我的 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)
}
具体来说,我在服务器端收到了空的请求正文。 有人可以帮我解决这个问题吗?
【问题讨论】:
-
我认为你不需要字符串化,你实际上是在字符串化2次
-
就像@Mir 说的,
requestJSON已经是一个字符串了 -
@slash197 - 我尝试不使用 JSON.stringify 但它没有帮助:( .
-
@slash197 - 我更新了问题,因为它重定向到 JSON.stringify 问题。我将 JSON.stringify(requestJSON) 更改为 requestJSON。
-
@DineshAppavoo 来自您的更新代码,您需要 stringfy