服务器端Go代码
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Authentication struct {
username string
password string
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/auth", func(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var auth Authentication
err := decoder.Decode(&auth)
if err != nil {
http.Error(w, "Failed to decode JSON", http.StatusBadRequest)
return
}
fmt.Printf("Received authentication: %+v\n", auth)
})
mux.Handle("/",http.FileServer(http.Dir("./static")))
fmt.Printf("Starting server at port 3000\n")
http.ListenAndServe(":3000", mux)
}
客户端Javascript代码:
//--Variables--//
let signin = document.getElementById("Signin");
let username = document.getElementById("Username");
let password = document.getElementById("Password");
signin.onclick = () => {
let data = {
username: username.value,
password: password.value,
};
sendData("/auth", data);
console.log(data.username, " ", data.password);
};
//--Functions--//
const sendData = (url, data) => {
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
};
我遇到的问题是,是的,POST 请求确实通过并且可以在服务器端看到,但我实际上看不到 POST 请求的内容。这是当请求到达时服务器端打印的内容: 收到身份验证:{用户名:密码:} 它是空的。 我的问题是:为什么它是空的,我对 Go 很陌生,并且不确定如何编码 Json 数据。 ChatGPT 说代码应该可以正常工作。
我搜索了其他 Stackoverflow 帖子并尝试了它们,但它们似乎从未起作用。可能是因为我做错了什么。
这里的问题是字段没有导出。将身份验证更改为以下内容应该会有所帮助
type Authentication struct {
Username string `json:"username"`
Password string `json:"password"
}