从Javascript中获取FormData并在Golang中处理数据

huangapple go评论138阅读模式
英文:

Fetch Data from FormData in Javascript and handle in Golang

问题

我正在尝试通过JavaScript从HTML网页中获取一些数据,并将其发送到我的Golang Web服务器。但是数据似乎没有被接收到。

这是我的JavaScript函数,在网页的下拉菜单中选择某个选项时调用:

async function onDataFormatSelect(dataFormat) 
{
  console.log('Change DataFormat', dataFormat);
  let formDataSelect = new FormData();
  formDataSelect.append("cmd", "change");
  const fetchoptions  = {
    method: 'POST',
    body: formDataSelect,
  };

  let r = await fetch('/myURL', fetchoptions);
  console.log('HTTP response code.', r.status);
  for (var pair of formDataSelect.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
  }
}

在我的Go Web服务器的SetupRoutes()函数中,URL获得了一个处理程序:

http.HandleFunc("/myURL", urlHandler)

这是我的处理程序:

func urlHandler(w http.ResponseWriter, r *http.Request) {
	

	if r.Method == "POST" {
		r.ParseForm()

		topicName := r.FormValue("topicName")
		cmd := r.FormValue("cmd")
		log.Println("action: " + cmd)
		switch cmd {
		...
		case "change": //Change DataFormat of Topic
			log.Println("cmd is " + cmd)
			newDataFormat := r.FormValue("dataFormat")
			//Call another function
		default:
			log.Println("unknown command: " + cmd)
		}

	} else {
		log.Println("using wrong method (GET)")
	}

	http.Redirect(w, r, appdata.Status.ProxyRedirect, http.StatusMovedPermanently)
}

JavaScript的输出是正确的。FormDataSelect被正确填充,但是在Go中没有"cmd"。不知何故,在另一个具有相同设置的函数中一切正常。

除了使用XMLHttpRequest,你能帮助我吗?或者你有其他的解决方法吗?

英文:

i'm trying to fetch some data from a HTML Webpage via Javascript to my Golang Webserver. But the Data does'nt seem to be received there.

This is my Javascript Function, which is called, when selecting something in my dropdown menu of my webpage:

async function onDataFormatSelect(dataFormat) 
    {
      console.log('Change DataFormat', dataFormat);
      let formDataSelect = new FormData();
      formDataSelect.append("cmd", "change");
      const fetchoptions  = {
        method: 'POST',
        body: formDataSelect,
      };

      let r = await fetch('/myURL', fetchoptions);
      console.log('HTTP response code.', r.status);
      for (var pair of formDataSelect.entries()) {
        console.log(pair[0]+ ', ' + pair[1]); 
      }
    }

In SetupRoutes() in my Go Webserver, the URL gets an Handler:

	http.HandleFunc("/myURL", urlHandler)

This is my Handler:

func urlHandler(w http.ResponseWriter, r *http.Request) {
	

	if r.Method == "POST" {
		r.ParseForm()

		topicName := r.FormValue("topicName")
		cmd := r.FormValue("cmd")
		log.Println("action: " + cmd)
		switch cmd {
		...
		case "change": //Change DataFormat of Topic
			log.Println("cmd is " + cmd)
			newDataFormat := r.FormValue("dataFormat")
			//Call another function
		default:
			log.Println("unknown command: " + cmd)
		}

	} else {
		log.Println("using wrong method (GET)")
	}

	http.Redirect(w, r, appdata.Status.ProxyRedirect, http.StatusMovedPermanently)
}

The Output of Javascript is correct. The FormDataSelect is filled correctly, but in Go the "cmd" is not there. Somehow in another Function with the same setup everything is working correctly.

Can you help me or do you have any Workaround for me beside using XMLHttpRequest?

答案1

得分: 2

FormData对象旨在支持文件上传,因此它们始终发送多部分请求。

请参阅Go的http模块文档

你正在使用parseForm,它的说明如下:

当Content-Type不是application/x-www-form-urlencoded时,请求体不会被读取,而r.PostForm会被初始化为非nil的空值。

你需要改用ParseMultipartForm

英文:

FormData objects are designed to support posting files so they always send multipart requests.

See the documentation for Go's http module.

You're using parseForm which says:

> when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value

You need to use ParseMultipartForm instead.

huangapple
  • 本文由 发表于 2021年5月25日 16:58:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/67684807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定