Golang 解决 HTTP 请求跨域问题

Golang 跨域 大约 1495 字

解决

请求头中添加Access-Control-Allow-OriginAccess-Control-Allow-Headers

func CustomRequest(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Add("Access-Control-Allow-Headers", "Content-Type")

    if req.Method == http.MethodOptions {
        return
    }

    // 省略
    _, _ = w.Write(resp)
}

func main() {
    http.HandleFunc("/CustomRequest", CustomRequest)

    if err := http.ListenAndServe(":8080", nil); err!= nil {
        log.Fatal(err)
    }
}

验证

使用jQuery验证。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8080/CustomRequest",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(
            {
                username: 'test123',
                password: 'testpwd',
            }),
            dataType: "json",
            success: function (result) {
                alert(JSON.stringify(result));
            },
            error: function (result) {
                alert(JSON.stringify(result));
            }
        });
    </script>
</head>
<body>

</body>
</html>

注意

Access-Control-Allow-OriginAccess-Control-Allow-Headers不能写在if req.Method == http.MethodOptions判断中。

阅读 192 · 发布于 2021-07-22

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批