给定一个发出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状态.
有人知道怎么解决这个问题吗?