英文:
why do i keep getting a "Method not allowed" on my html template whenever i try using http.MethodDelete?
问题
我正在使用http.MethodDelete来尝试从我的HTML模板中删除引用。每次我点击删除按钮时都会收到错误消息。
我尝试在我的HTML模板中使用以下代码:"<a class="delete-button" href="/quote/delete?quote_id={{ .QuoteID}}">Delete</a> ",但仍然出现错误。
英文:
I am using http.MethodDelete to try and delete quotes from my html template. Everytime i press the delete button i get the error message.
I tried using this inside my html template, "<a class="delete-button" href="/quote/delete?quote_id={{ .QuoteID}}">Delete</a> " but it still gives me the error.
答案1
得分: 0
我认为你的意思是这样的:
router.HandlerFunc(http.MethodDelete, "/quote/delete", app.quoteDelete)
<a class="delete-button" href="/quote/delete?quote_id={{ .QuoteID }}">Delete</a>
默认情况下,浏览器通过发送GET
请求来跟踪链接。它不会像你期望的那样发送DELETE
请求。
你可以使用JavaScript代码发送DELETE
请求。
看起来你的项目中没有编写任何JavaScript代码,所以一个快速的解决方法是修改服务器代码来处理POST
请求,并使用表单发送POST
请求到删除资源的端点:
router.HandlerFunc(http.MethodPost, "/quote/delete", app.quoteDelete)
<form action="/quote/delete?quote_id={{ .QuoteID }}" method="post">
<button type="submit">Delete</button>
</form>
请注意,表单不能用于发送DELETE
请求。表单元素的允许方法在MDN的表单元素文档中列出:
method
用于提交表单的HTTP方法。允许的方法/值仅限于(不区分大小写):
post
:使用POST方法,将表单数据作为请求体发送。get
(默认):使用GET方法,将表单数据附加到带有?分隔符的操作URL中。当表单没有副作用时使用此方法。dialog
:当表单位于<dialog>
内时,关闭对话框并在提交时触发提交事件,而不提交数据或清除表单。
关于HTTP请求方法的定义,请参阅HTTP请求方法。
英文:
I think you mean this:
router.HandlerFunc(http.MethodDelete, "/quote/delete", app.quoteDelete)
<a class="delete-button" href="/quote/delete?quote_id={{ .QuoteID}}">Delete</a>
By default, a browser follows a link by sending a GET
request. It does not send a DELETE
request as you expected.
You can send a DELETE
request using JavaScript code.
It seems that you haven't written any JavaScript code in your project, so a quick fix is to modify the server code to handle the POST
request and use a form to send a POST
request to the delete resource endpoint:
router.HandlerFunc(http.MethodPost, "/quote/delete", app.quoteDelete)
<form action="/quote/delete?quote_id={{ .QuoteID }}" method="post">
<button type="submit">Delete</button>
</form>
Please note that a form can not be used to send a DELETE
request. The allowed methods of a from element are listed on the doc for the Form element from MDN:
> method
>
> The HTTP method to submit the form with. The only allowed methods/values are (case insensitive):
>
> - post
: The POST method; form data sent as the request body.
> - get
(default): The GET; form data appended to the action URL with a ? separator. Use this method when the form has no side effects.
> - dialog
: When the form is inside a <dialog>
, closes the dialog and causes a submit event to be fired on submission, without submitting data or clearing the form.
And for the definition of HTTP request methods, see HTTP request methods.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论