如何从 Golang 中的 javascript XMLHttpRequest 读取 POST 数据?

How can you read POST data from a javascript XMLHttpRequest in Golang?

这是调用的 javascript 函数:

function cwk_submit_form() {
   var form = document.getElementById("FORM_ID")
   var XHR = new XMLHttpRequest();


   const FD = new FormData( form );
   for (const element of FD.entries()) {
       console.log(element)
   }

   XHR.open( "POST", "http://localhost:8080/post_data" );
   XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

   XHR.send( FD );
}

我把 console.log 留在那里是为了说明这确实打印出了正确的数据,这意味着问题似乎出在数据的传输方式上。

接收响应的Golang代码为:

func post_data(w http.ResponseWriter, r *http.Request) {
    log.Println("post was called")

    r.ParseForm()
    for key, value := range r.Form {
        log.Printf("%s = %s\n", key, value)
    }
}

此 for 循环不打印任何内容。

如果我像这样使用 HTML 表单提交:

<form action="//localhost:8080/post_data" method="POST">
    <input type="text" name="field1" value="" maxLength="20"/>
        
    <input type="text" name="field2" value="" maxLength="20"/>
        
    <input type="submit" value="Sign in"/>
</form>

那么上面的 Golang 代码工作正常,这让我相信 XMLHttpRequest 格式是问题所在。

你猜对了,你的js代码有问题

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

因此,当您发送的 Content-Type 和实际内容类型匹配 application/x-www-form-urlencoded 时,它将起作用,这发生在您的 HTML 表单案例中。

另一方面,当您使用 FormData 时,它将作为 multipart/form-data 发送。

您需要将 XHR.send(FD) 替换为 XHR.send(new URLSearchParams(FD)) 才能发送 application/x-www-form-urlencoded 中的数据。