douti19680318 2016-03-17 00:54 采纳率: 0%
浏览 75
已采纳

处理CORS表单提交

I have a very simple form being served from localhost:3000

<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>

On localhost:8080, I have a very simple go server:

package main

import (
    "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)
}

When I submit my form, I actually receive two requests! A POST and a GET! Here is my console after a SINGLE submit:

$ http://localhost:3000
$ POST
$ 
$ GET

Notice the GET request doesn't have an origin attached to it. I'm trying to perform some logic and then redirect the user to different url's based on success or failure. But I can't do this because the GET request immediately follows the POST request. I can use AJAX, no problem, but I was hoping to find a solution for a simple html form submission.

Any thoughts, ideas? Do all browsers follow the POST/Redirect/Get paradigm and I'm SOL?

Thanks.

  • 写回答

1条回答 默认 最新

  • doutui2883 2016-03-17 02:50
    关注

    I assume your form action is action="http://localhost:8080" because you said this is a cross origin request.

    The second GET request is the request for favicon (as elithrar points out in comments). Just do a log.Println(r.URL) to make sure. I am not sure why the browser does not add origin header to it though.

    You can redirect requests by replacing w.WriteHeader(http.StatusOK) by for example, http.Redirect(w, r, "http://localhost:3000/success.html", http.StatusSeeOther).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算