【问题标题】:How to send an string to server using fetch API如何使用 fetch API 将字符串发送到服务器
【发布时间】:2016-12-11 22:39:56
【问题描述】:

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

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

【问题讨论】:

    标签: javascript rest go fetch


    【解决方案1】:

    当您解码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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2015-10-20
      相关资源
      最近更新 更多