跨域请求被阻止

时间:2023-03-02

浏览:154

作者:佚名

积累知识,胜过积蓄金银!毕竟在##column_title##开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《跨域请求被阻止》,就带大家讲解一下golang知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

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

对清单的更改

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

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

理论要掌握,实操不能落!以上关于《跨域请求被阻止》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页