Javascript 如何使用fetchapi向服务器发送字符串
我正在使用Javascript 如何使用fetchapi向服务器发送字符串,javascript,rest,go,fetch,Javascript,Rest,Go,Fetch,我正在使用fetchAPI向我的服务器发出POST请求,请求是用Go编写的 fetch('http://localhost:8080', { method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ image:"hello" }) }
fetch
API向我的服务器发出POST
请求,请求是用Go编写的
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服务器上,我收到了帖子
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(请求正文)
在控制台中为我提供
我得到的唯一错误消息来自fetchapi。它会将以下错误打印到控制台
SyntaxError: Unexpected end of input
这来自.catch
声明
简而言之,如何在服务器上接收字符串?当您解码
req.Body
时,您无法再次读取请求正文,因为它已读取缓冲区,因此您将收到消息SyntaxError:Unexpected end of input
。如果要使用req.Body
上的值,必须将req.Body
的内容保存在一个变量中,如下所示
buf, err := ioutil.ReadAll(r.Body)
// check err for errors when you read r.Body
reader := bytes.NewReader(buf)
err = json.NewDecoder(reader).Decode(&t)
fmt.Println(string(buf))
if err != nil {
http.Error(rw, err.Error(), 400)
return
}
此外,您的JSON类似于{“image”:“hello”}
,因此您的结构应该是:
type test_struct struct {
Test string `json:"image"`
}
如果要将图像
值映射到测试