【问题标题】:React Native POST Method IssuesReact Native POST 方法问题
【发布时间】:2019-02-27 10:39:33
【问题描述】:

我已经阅读了许多与我类似的问题,但没有一个能解决我的问题, 我的 fetch (Get Method) 工作正常,但 (POST METHOD) 显示 JSON 输入意外结束

  fetch('http://monasabat-app.com/Queries/sub_cat.php', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: 3

        }),
      }).then((response) => response.json())
          .then((responseJson) => {
            this.setState({
                fsubCategory: responseJson.sub_cat
            })
          })
          .catch((error) => {
            console.error(error);
          });

}

这是我收到的 POSTMAN 回复

{
"sub_cat": [
    {
        "id": "4",
        "sub_cat": "sbu1",
        "img_path": "url"
    },
    {
        "id": "9",
        "sub_cat": "sub2",
        "img_path": "url"
    }
]
}

【问题讨论】:

    标签: json react-native post fetch fetch-api


    【解决方案1】:

    即使您在 postMan 中尝试使用 Content-Type: application/json,您也会注意到您没有收到任何响应。

    POST /Queries/sub_cat.php HTTP/1.1
    Host: monasabat-app.com
    Accept: application/json
    Content-Type: application/json
    Cache-Control: no-cache
    Postman-Token: c60774f8-1aaa-4cf8-8aa3-abcab34b05e3
    
    {id:3}
    

    unexpected end of JSON input 这是因为它试图解析一个空字符串。 所以这不是与 fetch 相关的问题,只需尝试以下操作以获得正确的响应:

    fetch('http://monasabat-app.com/Queries/sub_cat.php', {
        method: 'POST',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
        },
        body: 'id=3',
    })
    

    【讨论】:

    • SyntaxError: JSON 中位置 4 的意外数字
    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多