dongshanni1611 2019-05-08 01:33
浏览 187
已采纳

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

I can successfully send an XMLHttpRequest without parameters using this code:

template file:

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();

router:

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

But as soon as I try to add parameters I get a 405 error. I only change 2 lines, not sure what I am doing wrong:

template file:

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

router:

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

2条回答 默认 最新

  • dprxj1995 2019-05-08 01:54
    关注

    Your parameters in the open command are defined as URL query parameters (everything after the ?).
    But you added them as URL path parameters in the call to r.HandleFunc.

    Try handling the base path of /mytemplate with r.HandleFunc and then parsing the query parameters in your MyHandler function with r.URL.Query(). That should return a map of the query parameters, which you should be able to reference by key (param1, param2...).

    Stubbed out example below:

    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条)

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波