我想做的事我正在为我的 Golang 研究创建一个 Todo 应用程序。我想在 React with Golang 中读取来自 POST 请求的数据。代码去后端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) }
1 回答
慕神8447489
TA贡献1780条经验 获得超1个赞
我添加了这段代码,它解决了问题..
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
switch r.Method {
case "OPTIONS":
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
return
谢谢您的合作!
- 1 回答
- 0 关注
- 92 浏览
添加回答
举报
0/150
提交
取消