解决
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-Headersif req.Method == http.MethodOptions