我想做的事我正在為我的 Golang 研究創(chuàng)建一個(gè) Todo 應(yīng)用程序。我想在 React with Golang 中讀取來自 POST 請求的數(shù)據(jù)。代碼去后端package todosimport ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" "todo-app/auth" "github.com/joho/godotenv")type Todo struct { // UserID int `json:"userid"` Todo string `json:"todo"` CreatedAt time.Time `json:"createdat"` UpdatedAt time.Time `json:"updatedat"`}type TodoBody struct { Todo string `json:"todo"`}func CreateTodo(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "*") w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000") w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Set("Access-Control-Allow-Headers", "*") e := godotenv.Load() if e != nil { log.Fatal(e) } dbConnectionInfo := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/go_todo", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD")) db, err := sql.Open("mysql", dbConnectionInfo) if err != nil { log.Fatal(err) } defer db.Close() tokenString := r.Header.Get("Authorization") tokenString = strings.TrimPrefix(tokenString, "Bearer ") log.Printf("request token=%s\n", tokenString) body, err := ioutil.ReadAll(r.Body) if err != nil { log.Fatal(err) } log.Printf("request body=%s\n", body) var data TodoBody if err := json.Unmarshal(body, &data); err != nil { log.Println(err) }
我想從 React 發(fā)布到在 Golang 中創(chuàng)建的 API
呼喚遠(yuǎn)方
2022-12-26 10:42:58