所以我有了这个Go http处理程序,它将一些POST内容存储到数据存储中,并检索一些其他信息作为响应。在后端,我使用:
func handleMessageQueue(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == "POST" {
c := appengine.NewContext(r)
body, _ := ioutil.ReadAll(r.Body)
auth := string(body[:])
r.Body.Close()
q := datastore.NewQuery("Message").Order("-Date")
var msg []Message
key, err := q.GetAll(c, &msg)
if err != nil {
c.Errorf("fetching msg: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
jsonMsg, err := json.Marshal(msg)
msgstr := string(jsonMsg)
fmt.Fprint(w, msgstr)
return
}
}
在我的firefox OS应用程序中,我使用:
var message = "content";
request = new XMLHttpRequest();
request.open('POST', 'http://localhost:8080/msgs', true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
data = JSON.parse(request.responseText);
console.log(data);
} else {
// We reached our target server, but it returned an error
console.log("server error");
}
};
request.onerror = function () {
// There was a connection error of some sort
console.log("connection error");
};
request.send(message);
即将到来的部分都是正常工作的。然而,我的响应被阻止了。给我以下信息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/msgs. This can be fixed by moving the resource to the same domain or enabling CORS.
我尝试了很多其他方法,但我不可能只从服务器获得响应。但是,当我将Go POST方法更改为GET并通过浏览器访问页面时,我得到了我非常想要的数据。我真的不能确定哪一端出错了,原因是:可能是Go不应该阻止这些类型的请求,但也可能是我的javascript是非法的。
https://stackoverflow.com/questions/22363268
复制相似问题