Problem with HTTP form data

blov · · 385 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi everyone, I am having an issue parsing a POST request with form data to a go http handler. </p> <p>I&#39;m making a call using the following javascript:</p> <pre><code>postForm: (url, formName) =&gt; { return new Promise((resolve, reject) =&gt; { const form = document.forms.namedItem(formName); if (typeof form === &#39;undefined&#39;) { reject(`failed to find form named ${formName}`); } const data = new FormData(form); const request = new XMLHttpRequest(); request.onreadystatechange = () =&gt; { if(request.readyState === 1) { request.setRequestHeader(&#34;content-type&#34;, &#34;application/x-www-form-urlencoded&#34;); } if(request.readyState &lt; 4) { return; } if (request.readyState === 4 &amp;&amp; request.status === 200) { return resolve(request); } return reject(request.statusText); }; request.open(&#39;post&#39;, 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(&#34;email&#34;) 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&#39;t tell if this is a problem on the go or javascript side. The form data looks like this:</p> <p>&#34;&#34;firstName&#34;</p> <p>David ------WebKitFormBoundarylsARpbisZsolgWUA ...+30 more&#34;</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&#39;s <code>x-www-form-urlencoded</code> instead.</p></pre>everdev: <pre><p>To isolate the error, try it&#39;s simplest form: Send a POST request via Postman to your API endpoint. If it comes through fine, then it&#39;s your JS.</p> <p>Your Go snippet is simple enough that I can&#39;t see an error in those couple lines.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

385 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传