所以我已经有了这个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是非法的。
对我来说似乎(我不写这个作为答案,因为我不确定)你没有设置请求上的内容类型。从Mozilla的TFM就这个问题:'如果使用POST向服务器发送数据,则使用HTTP POST请求发送到服务器的数据的内容类型是application/x-www-form-urlencoded,multipart /表单数据或文本/纯文本' –