给定一个发出HTTP请求的客户端

<!DOCTYPE html>
<html>
    <body>
        <script>
            fetch('http://localhost:3000/messages', {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify({ data: 'foo' })
            })
            .then(async response => {
                console.log(await response.json());
            });
        </script>
    </body>
</html>

API服务器不处理请求,请求处理程序应充当代理并将请求发送到另一台服务器

import (
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/messages", handleRequest)

    http.ListenAndServe(":3000", mux)
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "*")
    w.Header().Set("Access-Control-Allow-Methods", "*")

    targetUrl, _ := url.Parse("http://localhost:3001/messages")

    proxy := httputil.NewSingleHostReverseProxy(targetUrl)
    proxy.ServeHTTP(w, r)
}

目标服务器应处理该请求并发回响应

import (
    "encoding/json"
    "net/http"
)

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/messages", handleRequest)

    http.ListenAndServe(":3001", mux)
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "*")
    w.Header().Set("Access-Control-Allow-Methods", "*")

    w.WriteHeader(http.StatusOK)

    json.NewEncoder(w).Encode("wine 吧")
}

我启动两台服务器并运行.html文件,我希望

wine 吧

在控制台中.但不幸的是我弄错了

CORS策略已阻止访问从源‘Null’获取‘http://localhost:3000/messages’‘:对印前判断请求的响应未通过访问控制判断:它没有HTTPok状态.

enter image description here

有人知道怎么解决这个问题吗?

推荐答案

您需要在代理中添加不同的路径来处理印前判断请求. 您的代理应该是这样的:

func handleRequest(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "*")
    w.Header().Set("Access-Control-Allow-Methods", "*")

    if r.Method == "OPTIONS" {
        w.WriteHeader(http.StatusOK)
        return
    }
    targetUrl, _ := url.Parse("http://localhost:3001")

    proxy := httputil.NewSingleHostReverseProxy(targetUrl)
    proxy.ServeHTTP(w, r)
}

请注意更改:

  1. OPTION个请求(印前判断)不会传递到服务器,您只需发送OK状态即可接受它们.

  2. (与CORS问题无关)目标URL不应包含/message部分.路径部分已存在于您的请求中,您不应重复.

此外,您还需要更改服务器代码并删除这些标头:

// w.Header().Set("Access-Control-Allow-Origin", "*")
// w.Header().Set("Access-Control-Allow-Headers", "*")
// w.Header().Set("Access-Control-Allow-Methods", "*")

它们已经由代理设置.服务器不再响应Web浏览器.

Go相关问答推荐

GO框架Echo中间件的使用

确定果朗CSV行中的字节数

不接受来自 stdin 的重复输入

将这两个函数合二为一的惯用方法

Golang text/template中的startswith函数 - 入门教程

最长连续重复的字符golang

gopacket:IP-in-IP 数据包上的解码层

我的神经网络(从头开始)训练,让它离目标更远

如何使用管理员权限启动 powershell 进程并重定向标准输入 (os.exec)

如何在 Go 中编写示例测试?

从Go中的随机日期开始以天为单位获取时间

从数据库中带有 imageurl 的文件夹中获取图像,并在我的浏览器中用 golang 中的 echo 显示

无法使用 Golang 扫描文件路径

fmt.Printf() 标志 '0' 不会被字符串忽略

Golang invopop jsonschema 使用 if/then/else

Golang泛型在用作 map 元素时不起作用

go 是否对 struct 使用空间填充之类的东西?

为什么 go.mod 中的所有依赖都是间接的?

有没有办法在一个 goroutine 返回后延迟后取消上下文?

如何将类型转换为字节数组golang