【发布时间】:2016-12-11 22:39:56
【问题描述】:
我正在使用 fetch API 向我用 Go 编写的服务器发出 POST 请求...
fetch('http://localhost:8080', {
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
image:"hello"
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("response");
})
.catch(function(error) {
console.log(error);
})
在我的 Go 服务器上,我收到了 POST...
type test_struct struct {
Test string
}
func GetImage(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
var t test_struct
if req.Body == nil {
http.Error(rw, "Please send a request body", 400)
return
}
err := json.NewDecoder(req.Body).Decode(&t)
fmt.Println(req.Body)
if err != nil {
http.Error(rw, err.Error(), 400)
return
}
fmt.Println(t.Test);
}
发出POST 请求。我知道这一点是因为fmt.Println(t.Test) 正在向控制台打印一个空行。
fmt.Println(req.Body) 在控制台中给我<nil>。
我收到的唯一错误消息来自 fetch API。它向控制台打印以下错误...
SyntaxError: Unexpected end of input
这来自.catch 声明。
简而言之,我如何才能在服务器上接收到字符串?
【问题讨论】:
标签: javascript rest go fetch