如果方法是 DELETE,我似乎会得到 Go http.Request 的空正文内容。但如果我将方法更改为 POST,那么正文内容就会给出我期望的内容。
我的 golang 中的相关代码如下所示:
import(
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func Delete(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
qs := r.Form
log.Println(qs)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/profile", Delete).Methods("POST")
router.HandleFunc("/profile", Delete).Methods("DELETE")
}
现在,当我从浏览器运行此 JavaScript 代码时:
fetch(sendurl,{
method:"POST",
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body:"data="+project.encodeFormURIComponent(JSON.stringify({"ids":[1032,1033]}))
})
.then(response=>{
if(response.ok)
return response.json();
})
.then(result=>{
console.log(result);
})
我在 Golang 代码的 qs[ids]
中看到了一组很好的数字。但是,如果我在 JavaScript 中将 method:"POST"
更改为 method:"DELETE"
,则 qs
为空。
我做错了什么?
更新
带有 DELETE 方法的 JavaScript 可以按照人们通常期望的方式填充 Go qs
变量:
fetch(sendurl+"?data="+project.encodeFormURIComponent(JSON.stringify({"ids":[1032,1033]})),{
method:"DELETE",
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response=>{
if(response.ok)
return response.json();
})
.then(result=>{
console.log(result);
})
所以,当使用 DELETE
方法时,Go 似乎会忽略 JavaScript body
参数,但它会尊重 API 端点 url 中的查询字符串内容?为什么会这样?
最佳答案
https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
查询字符串是请求的target-uri的一部分;换句话说,查询字符串是标识符的一部分,而不是它的附带修饰符。但请求的消息正文不是标识符的一部分。
因此,您的本地框架或转发您的请求的任何其他通用组件不需要为消息正文提供支持。
想想 C 中的“未定义行为”。
关于rest - 我的其余 api 端点中的删除请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011487/