如果方法是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);
})
我qs[ids]
在Golang代码中看到了很多数字。但是,如果我在JavaScript中将更改method:"POST"
为method:"DELETE"
,qs
则为空。
我究竟做错了什么?
更新
带有DELETE方法的JavaScript可以按照qs
通常期望的方式填充Go 变量:
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);
})
如此看来,使用方法body
时Go会忽略JavaScript 参数DELETE
,但会尊重API端点url中的查询字符串内容吗?为什么会这样呢?
https://tools.ietf.org/html/rfc7231#section-4.3.5
DELETE请求消息中的有效负载没有定义的语义;在DELETE请求上发送有效内容正文可能会导致某些现有实现拒绝该请求。
查询字符串是请求的target-uri的一部分;换句话说,查询字符串是标识符的一部分,而不是它的附带修饰符。但是请求的消息正文不是标识符的一部分。
因此,不需要您的本地框架或转发您的请求的任何其他通用组件即可为消息正文提供支持。
在C语言中考虑“未定义的行为”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句