Golang REST API的PUT和DELETE请求在使用JavaScript从HTML页面调用时无法正常工作。

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

Golang REST API PUT and DELETE request doest work when calling from HTML page using Javascript

问题

我正在尝试使用Go编写一个REST API,在Postman中运行时,所有的方法都正常工作,但是当我使用JavaScript函数从HTML页面调用PUT和Delete方法时,它们不起作用。是否有其他的替代方法?

以下是我在main.go文件中的Go处理程序:

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", HomePageHandler).Methods("GET")
    router.HandleFunc("/demo", CreateDemoDetail).Methods("POST") // 添加新行
    router.HandleFunc("/demo", GetAllDemoDetails).Methods("GET") // 获取所有详情
    router.HandleFunc("/demo/{id}", GetDemoDetail).Methods("GET") // 获取单行
    router.HandleFunc("/demo", UpdateDemoDetails).Methods("PUT") // 更新单行
    router.HandleFunc("/demo", DeleteDemo).Methods("DELETE")     // 删除单行
    log.Fatal(http.ListenAndServe(":8080", router))
}

以下是调用处理程序的JavaScript函数:

function submitForm(reqtype){
    var form = document.getElementById("demoform");      
  
    if (reqtype == "Delete"){
        form.action = 'http://localhost:8080/demo';
        form.method='PUT';      
    }
    if (reqtype == "Update"){
        form.action = 'http://localhost:8080/demo';
        form.method='DELETE';      
    }      
  
    form.submit();
}
</script>

如果我将处理程序更改为router.HandleFunc("/updatedemo", UpdateDemoDetails).Methods("POST"),然后从JavaScript中使用/demo和方法为POST调用它,它可以正常工作,但是当使用/demo/和方法为PUT/Delete时就不行了。

有趣的是,当端点为/demo/或get demo,方法为POST/GET/PUT/Delete时,它在Postman中完美运行。但是在使用HTML表单和JavaScript调用时却不行。

我应该采取什么最佳方法?

英文:

I am trying to write a REST API in Go, all the methods are working fine when I run through postman, but when calling the PUT and Delete methods from the HTML page using JAVA Script function it's not working. Are there any alternatives for the same?

Here are my Go Handlers in main.go file.

func main() {
	router := mux.NewRouter()
	router.HandleFunc(&quot;/&quot;, HomePageHandler).Methods(&quot;GET&quot;)
	router.HandleFunc(&quot;/demo&quot;, CreateDemoDetail).Methods(&quot;POST&quot;) // Add New row
	router.HandleFunc(&quot;/demo&quot;, GetAllDemoDetails).Methods(&quot;GET&quot;) // Fetch all details
	router.HandleFunc(&quot;/demo/{id}&quot;, GetDemoDetail).Methods(&quot;GET&quot;) // Fetch Single row
	router.HandleFunc(&quot;/demo&quot;, UpdateDemoDetails).Methods(&quot;PUT&quot;) // Update Single row
	router.HandleFunc(&quot;/demo&quot;, DeleteDemo).Methods(&quot;DELETE&quot;)     // Delete Single row
	log.Fatal(http.ListenAndServe(&quot;:8080&quot;, router))
}

Following is the Java Script function which calls the Handlers,

 function submitForm(reqtype){
          var form = document.getElementById(&quot;demoform&quot;);      
    
          if (reqtype == &quot;Delete&quot;){
            form.action = &#39;http://localhost:8080/demo&#39;;
           form.method=&#39;PUT&#39;;      
          }
          if (reqtype == &quot;Update&quot;){
            form.action = &#39;http://localhost:8080/demo&#39;;
            form.method=&#39;DELETE&#39;;      
    
          }      
    
          form.submit();
        }
      &lt;/script&gt;

If i change the handler to
router.HandleFunc("/updatedemo", UpdateDemoDetails).Methods("POST") than just /demo and the method to POST it works from java script, but not when its demo/ and the method is PUT/Delete.

Interestingly it works perfectly with Postman when the endpoints are demo/ or get demo and method are POST/GET/PUT/Delete. But not from HTML form with Javascript call.

What is the best approach I should take?

答案1

得分: 1

method attribute只支持GET和POST HTTP动词。

要使用PUT或DELETE,您需要使用fetchXMLHttpRequest进行请求。

英文:

The method attribute only supports the GET and POST HTTP verbs.

To use PUT or DELETE you would need to make the request with fetch or XMLHttpRequest.

答案2

得分: -3

如果你的网页服务器与你的 API 运行在不同的主机/端口上,我建议你查看 CORS(https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)。

如评论中所建议的,检查你的浏览器的 JS 日志/控制台。如果 CORS 是你的问题,那里应该会有清晰的错误信息。

英文:

I would look at CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) if your web server is running other host / port than your API.

As suggested in comments, check your browsers JS logs / console. There should be clear error messages if CORS is your problem.

huangapple
  • 本文由 发表于 2021年7月26日 19:35:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/68529144.html
匿名

发表评论

匿名网友

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

确定