如何使用 fetch API 将字符串发送到服务器

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>

我收到的唯一错误消息来自提取 API。它向控制台打印以下错误...

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"`
}

如果要将 image 值映射到 Test