How to send an string to server using fetch API

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

How to send an string to server using fetch API

问题

我正在使用fetch API向我的Go服务器发起POST请求...

  1. fetch('http://localhost:8080', {
  2. method:'POST',
  3. headers: {
  4. 'Accept': 'application/json',
  5. 'Content-Type': 'application/json'
  6. },
  7. body: JSON.stringify({
  8. image:"hello"
  9. })
  10. })
  11. .then((response) => response.json())
  12. .then((responseJson) => {
  13. console.log("response");
  14. })
  15. .catch(function(error) {
  16. console.log(error);
  17. })

在我的Go服务器上,我正在接收这个POST请求...

  1. type test_struct struct {
  2. Test string
  3. }
  4. func GetImage(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
  5. var t test_struct
  6. if req.Body == nil {
  7. http.Error(rw, "Please send a request body", 400)
  8. return
  9. }
  10. err := json.NewDecoder(req.Body).Decode(&t)
  11. fmt.Println(req.Body)
  12. if err != nil {
  13. http.Error(rw, err.Error(), 400)
  14. return
  15. }
  16. fmt.Println(t.Test);
  17. }

POST请求已经发送。我知道这一点,因为fmt.Println(t.Test)在控制台上打印了一个空行。

fmt.Println(req.Body)在控制台上给出了<nil>

我只收到来自fetch API的错误消息。它在控制台上打印了以下错误...

  1. SyntaxError: Unexpected end of input

这是来自.catch声明的错误。

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

英文:

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

  1. fetch(&#39;http://localhost:8080&#39;, {
  2. method:&#39;POST&#39;,
  3. headers: {
  4. &#39;Accept&#39;: &#39;application/json&#39;,
  5. &#39;Content-Type&#39;: &#39;application/json&#39;
  6. },
  7. body: JSON.stringify({
  8. image:&quot;hello&quot;
  9. })
  10. })
  11. .then((response) =&gt; response.json())
  12. .then((responseJson) =&gt; {
  13. console.log(&quot;response&quot;);
  14. })
  15. .catch(function(error) {
  16. console.log(error);
  17. })

On my Go server I am receiving the POST...

  1. type test_struct struct {
  2. Test string
  3. }
  4. func GetImage(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
  5. var t test_struct
  6. if req.Body == nil {
  7. http.Error(rw, &quot;Please send a request body&quot;, 400)
  8. return
  9. }
  10. err := json.NewDecoder(req.Body).Decode(&amp;t)
  11. fmt.Println(req.Body)
  12. if err != nil {
  13. http.Error(rw, err.Error(), 400)
  14. return
  15. }
  16. fmt.Println(t.Test);
  17. }

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

  1. 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的内容保存在一个变量中,类似这样的方式。

  1. buf, err := ioutil.ReadAll(r.Body)
  2. // 在读取r.Body时检查错误
  3. reader := bytes.NewReader(buf)
  4. err = json.NewDecoder(reader).Decode(&t)
  5. fmt.Println(string(buf))
  6. if err != nil {
  7. http.Error(rw, err.Error(), 400)
  8. return
  9. }

另外,你的JSON格式是{"image":"hello"},所以你的结构体应该是:

  1. type test_struct struct {
  2. Test string `json:"image"`
  3. }

如果你想将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.

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

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

  1. type test_struct struct {
  2. Test string `json:&quot;image&quot;`
  3. }

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:

确定