向XMLHttpRequests添加参数会导致405错误

时间:2019-05-08 01:33:01

标签: javascript go xmlhttprequest

我可以使用以下代码成功发送不带参数的XMLHttpRequest:

模板文件:

xhr.open('POST', '/mytemplate');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
   if (xhr.status == 200) {
      alert('success');
   }
   else {
      alert('failed:' + xhr.status);
   }
}
xhr.send();

路由器:

r.HandleFunc("/mytemplate", MyHandler).Methods("POST")

但是,一旦我尝试添加参数,就会出现405错误。我只更改2行,不确定自己在做什么错:

模板文件:

xhr.open('POST', '/mytemplate?param1='+var1+'&param2='+var2+'&param3='+var3);

路由器:

r.HandleFunc("/mytemplate/{param1}/{param2}/{param2}", MyHandler).Methods("POST")

2 个答案:

答案 0 :(得分:2)

您将open命令中的参数定义为URL查询参数(?之后的所有内容)。
但是您在对r.HandleFunc的调用中将它们添加为URL路径参数。

尝试使用/mytemplate处理r.HandleFunc的基本路径,然后使用MyHandler解析r.URL.Query()函数中的查询参数。那应该返回查询参数的映射,您应该能够通过键(param1param2 ...)来引用。

下面的例子很简单

func myHandler(w http.ResponseWriter, r *http.Request) {
    //get the query vals
    values := r.URL.Query()

    //parse specific params
    param1 := values["param1"]

    //do other stuff
}

func main() {
    //define the handler
    http.HandleFunc("/myHandlerPath", myHandler)

    // do some other stuff?
    // ...

    // serve up the endpoint
    log.Fatal(http.ListenAndServe(":8081", nil))
}

答案 1 :(得分:2)

您正在处理的路线如下:

/mytemplate/some/variables/here

但是您正在使用查询参数将请求发送到/mytemplate,如下所示:

/mytemplate?param1=some&param2=variables&param3=here

Gorilla Mux在这些方面不匹配。如果要匹配查询参数而不是URL参数,请参阅Gorilla Mux documentation中的.Queries方法。