首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >跨域请求被阻止

跨域请求被阻止
EN

Stack Overflow用户
提问于 2014-03-13 04:38:11
回答 2查看 168.4K关注 0票数 25

所以我有了这个Go http处理程序,它将一些POST内容存储到数据存储中,并检索一些其他信息作为响应。在后端,我使用:

代码语言:javascript
复制
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应用程序中,我使用:

代码语言:javascript
复制
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);

即将到来的部分都是正常工作的。然而,我的响应被阻止了。给我以下信息:

代码语言:javascript
复制
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是非法的。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22363268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档