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

处理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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)