Go 解决 HTTP 请求跨域问题

Go 跨域 HTTP About 1,495 words

解决

请求头中添加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判断中。

Views: 2,647 · Posted: 2021-07-21

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh