<p>Hi everyone, I am having an issue parsing a POST request with form data to a go http handler. </p>
<p>I'm making a call using the following javascript:</p>
<pre><code>postForm: (url, formName) => {
return new Promise((resolve, reject) => {
const form = document.forms.namedItem(formName);
if (typeof form === 'undefined') {
reject(`failed to find form named ${formName}`);
}
const data = new FormData(form);
const request = new XMLHttpRequest();
request.onreadystatechange = () => {
if(request.readyState === 1) {
request.setRequestHeader("content-type", "application/x-www-form-urlencoded");
}
if(request.readyState < 4) {
return;
}
if (request.readyState === 4 && request.status === 200) {
return resolve(request);
}
return reject(request.statusText);
};
request.open('post', url);
request.send(data);
});
}
</code></pre>
<p>And handling it using the following go handler:</p>
<pre><code>if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
email := r.FormValue("email")
fmt.Println(email)
</code></pre>
<p>The problem is, when I run r.ParseForm(), I end up with what looks like malformed form data. I can't tell if this is a problem on the go or javascript side. The form data looks like this:</p>
<p>""firstName"</p>
<p>David
------WebKitFormBoundarylsARpbisZsolgWUA
...+30 more"</p>
<p>Has anyone working with HTML forms experienced this before? Thank you for any help.</p>
<hr/>**评论:**<br/><br/>iroflmaowtf: <pre><p>I think you need to call r[equest].ParseMultipartForm()</p></pre>hobbified: <pre><p>You seem to be sending a multipart body, but claiming it's <code>x-www-form-urlencoded</code> instead.</p></pre>everdev: <pre><p>To isolate the error, try it's simplest form:
Send a POST request via Postman to your API endpoint. If it comes through fine, then it's your JS.</p>
<p>Your Go snippet is simple enough that I can't see an error in those couple lines.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传