ajax - 跨域请求被阻止

标签 ajax google-app-engine go cors firefox-os

所以我有了这个 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 是非法的。

最佳答案

@Egidius,在创建 XMLHttpRequest 时,你应该使用

var xhr = new XMLHttpRequest({mozSystem: true});

什么是 mozSystem?

mozSystem bool 值:将此标志设置为 true 允许进行跨站点连接,而无需服务器选择使用 CORS。需要设置 mozAnon: true,即不能与发送 cookie 或其他用户凭据结合使用。这仅适用于特权(已审核)应用程序;它不适用于 Firefox 中加载的任意网页。

list 更改

在您的 list 中,不要忘记在您的权限中包含这一行:

"permissions": {
       "systemXHR" : {},
}

关于ajax - 跨域请求被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22363268/

相关文章:

php - 当ajax仍在运行/锁定页面时加载另一个页面?

javascript - 如何在javascript中转义单引号、双引号和反作用?

jquery - 在ajax成功函数中接收.csv文件作为数据

python - 如何在 Google App Engine 中打印?

google-app-engine - 使用 GAE 限制对静态文件的访问

python - 如何使用scrapy处理escaped_fragment

go - 如何将数据从 CSV 导入到 MySQL

csv - 并发写入csv : “slice bounds out of range”

windows - Gopath环境错误

java - Google App Engine JDO 增强失败