Golang No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问

时间:2018-01-27 01:10:30

标签: javascript go cookies

我正在尝试测试我是否在域A中,域A客户端是否可以将域B cookie发送到域B.

这是我的golang代码

package main

import (
    "fmt"
    "net/http"
    "log"
    "time"
    "encoding/json"
)

func setCookie(w http.ResponseWriter, r *http.Request) {
    expiration := time.Now().Add(365 * 24 * time.Hour)
    cookie := http.Cookie{Path: "/test_receive_cookie", Name: "test_cors", Value: "test_cors", Expires: expiration}
    http.SetCookie(w, &cookie)
    fmt.Fprintf(w, "Success")
}

func receiveCookie(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.Cookies())

    data := make(map[string]interface{})
    for _, cookie := range r.Cookies() {
        data[cookie.Name] = cookie.Value
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(data)
}

func main() {
    http.HandleFunc("/set_cookie", setCookie)
    http.HandleFunc("/test_receive_cookie", receiveCookie)
    err := http.ListenAndServe(":8012", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

我首先点击http://localhost:8012/set_cookie,然后使用此library打开包含javascript的html文件

        this._xhr.get(
            "http://localhost:8012/test_receive_cookie", 
            { headers: { "Access-Control-Allow-Origin": "*" }},
            function(err, resp) {
                console.log(resp);
                console.log(err);
            });

发生了以下情况

  1. 浏览器返回
  2. Failed to load http://localhost:8012/test_receive_cookie: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

    1. 我的服务器从[]

    2. 打印fmt.Println(r.Cookies())
    3. 如果我点击http://localhost:8012/test_receive_cookie我可以看到我设置的cookie在浏览器上打印出来,但当我打开调用端点的html时,服务器将有空cookie

    4. 我的问题是如何使用客户端代码将cookie传回http://localhost:8012/test_receive_cookie

      我错过了一些配置代码吗?

1 个答案:

答案 0 :(得分:2)

您需要Go服务器发送Access-Control-Allow-Origin标头,客户端无法提供它们(请参阅CORS)。

如果您更新服务器以添加此标头,则客户端将停止抛出错误。

实施例

w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")

参考:

Enable CORS in Golang