[英]How to send an string to server using fetch API
I am using the fetch
API to make a POST
request to my server written in Go... 我正在使用
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);
})
On my Go server I am receiving the POST
... 在我的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);
}
The POST
request is made. 发出
POST
请求。 I know this because fmt.Println(t.Test)
is printing a blank line to the console. 我知道这是因为
fmt.Println(t.Test)
将空白行打印到控制台。
fmt.Println(req.Body)
gives me <nil>
in the console. fmt.Println(req.Body)
在控制台中给了我<nil>
。
The only error message I get is from the fetch API. 我收到的唯一错误消息是来自访存API。 It prints to the console the following error...
它向控制台显示以下错误...
SyntaxError: Unexpected end of input
this is coming from the .catch
declaration. 这来自
.catch
声明。
In short, how can I receive the string on the server? 简而言之,如何在服务器上接收字符串?
When you decode req.Body
, you can't read again the request body, because it's already read the buffer, for that reason you're getting the message SyntaxError: Unexpected end of input
. 解码
req.Body
,无法再次读取请求正文,因为它已经读取了缓冲区,因此,您将收到消息SyntaxError: Unexpected end of input
。 If you want to use the value on req.Body
, you must to save the content of req.Body
in a variable, something like this. 如果要使用
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
}
Also, your JSON is like {"image":"hello"}
, so your struct should be: 另外,您的JSON类似于
{"image":"hello"}
,因此您的结构应为:
type test_struct struct {
Test string `json:"image"`
}
If you want to map the image
value into Test
如果要将
image
值映射到Test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.