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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料