我從 localhost:3000 提供了一個(gè)非常簡(jiǎn)單的表單<form id="my-HTML-form" action="http://localhost:8080" method="POST"> <input type="text" placeholder="Username" name="username" /> <input type="password" placeholder="Password" name="password" /> <input type="hidden" name="form-id" value="login" /> <button type="submit">Submit</button></form>在 localhost:8080 上,我有一個(gè)非常簡(jiǎn)單的 go 服務(wù)器:package mainimport ( "log" "net/http")func main() { // Start the server http.HandleFunc("/", handler) serverErr := http.ListenAndServe(":8080", nil) if serverErr != nil { log.Println("Error starting server") log.Fatal(serverErr) }}func handler(w http.ResponseWriter, r *http.Request) { log.Println(r.Header.Get("Origin")) log.Println(r.Method) w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Origin, X-CSRF-Token") w.WriteHeader(http.StatusOK)}當(dāng)我提交表單時(shí),我實(shí)際上收到了兩個(gè)請(qǐng)求!一個(gè) POST 和一個(gè) GET!這是單次提交后我的控制臺(tái):$ http://localhost:3000$ POST$ $ GET請(qǐng)注意 GET 請(qǐng)求沒有附加源。我正在嘗試執(zhí)行一些邏輯,然后根據(jù)成功或失敗將用戶重定向到不同的 url。但我不能這樣做,因?yàn)?GET 請(qǐng)求緊跟在 POST 請(qǐng)求之后。我可以使用 AJAX,沒問題,但我希望找到一個(gè)簡(jiǎn)單的 html 表單提交的解決方案。任何想法,想法?是否所有瀏覽器都遵循POST/Redirect/Get范式,而我是 SOL?
1 回答

心有法竹
TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
我假設(shè)您的表單操作是action="http://localhost:8080"
因?yàn)槟f這是一個(gè)跨源請(qǐng)求。
第二個(gè) GET 請(qǐng)求是對(duì) favicon 的請(qǐng)求(正如 elithrar 在評(píng)論中指出的那樣)。做一個(gè)log.Println(r.URL)
來確保。我不確定為什么瀏覽器不向它添加原始標(biāo)題。
您可以通過替換w.WriteHeader(http.StatusOK)
為例如, 重定向請(qǐng)求http.Redirect(w, r, "http://localhost:3000/success.html", http.StatusSeeOther)
。
- 1 回答
- 0 關(guān)注
- 169 瀏覽
添加回答
舉報(bào)
0/150
提交
取消