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

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

报告相同问题?