How to send an string to server using fetch API

huangapple go评论76阅读模式
英文:

How to send an string to server using fetch API

问题

我正在使用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声明的错误。

简而言之,我如何在服务器上接收到这个字符串?

英文:

I am using the fetch API to make a POST request to my server written in Go...

fetch(&#39;http://localhost:8080&#39;, {
	method:&#39;POST&#39;,
	headers: {
		&#39;Accept&#39;: &#39;application/json&#39;,
		&#39;Content-Type&#39;: &#39;application/json&#39;
	},
	body: JSON.stringify({
		image:&quot;hello&quot;
	})
})
.then((response) =&gt; response.json())
.then((responseJson) =&gt; {
	console.log(&quot;response&quot;);
})
.catch(function(error) {
	console.log(error);
})

On my Go server I am receiving the 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, &quot;Please send a request body&quot;, 400)
	    return
    }
    err := json.NewDecoder(req.Body).Decode(&amp;t)
    fmt.Println(req.Body)
    if err != nil {
	    http.Error(rw, err.Error(), 400)
        return
    }
    fmt.Println(t.Test);
}

The POST request is made. I know this because fmt.Println(t.Test) is printing a blank line to the console.

fmt.Println(req.Body) gives me &lt;nil&gt; in the console.

The only error message I get is from the fetch API. It prints to the console the following error...

SyntaxError: Unexpected end of input

this is coming from the .catch declaration.

In short, how can I receive the string on the server?

答案1

得分: 3

当你解码req.Body时,你不能再次读取请求体,因为它已经读取了缓冲区,所以你会收到SyntaxError: Unexpected end of input的错误消息。如果你想使用req.Body的值,你必须将req.Body的内容保存在一个变量中,类似这样的方式。

buf, err := ioutil.ReadAll(r.Body)
// 在读取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"`
}

如果你想将image的值映射到Test字段。

英文:

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. 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.

buf, err := ioutil.ReadAll(r.Body)
// check err for errors when you read r.Body
reader := bytes.NewReader(buf)
err = json.NewDecoder(reader).Decode(&amp;t)
fmt.Println(string(buf))
if err != nil {
    http.Error(rw, err.Error(), 400)
    return
}

Also, your JSON is like {&quot;image&quot;:&quot;hello&quot;}, so your struct should be:

type test_struct struct {
    Test string `json:&quot;image&quot;`
}

If you want to map the image value into Test

huangapple
  • 本文由 发表于 2016年12月12日 06:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/41091950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定