简体   繁体   中英

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

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. I know this because fmt.Println(t.Test) is printing a blank line to the console.

fmt.Println(req.Body) gives me <nil> 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?

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(&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:

type test_struct struct {
    Test string `json:"image"`
}

If you want to map the image value into Test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM