【问题标题】:How can I pass POST parameters in fetch request? - React Native如何在获取请求中传递 POST 参数? - 反应原生
【发布时间】:2017-02-02 19:49:51
【问题描述】:

这是我的代码:

componentWillMount() {
  fetch("http://localmachine/localservice/webservice/rest/server.php", {
    method: 'POST',
    body: JSON.stringify({
      wstoken: 'any_token',
      wsfunction: 'any_function',
      moodlewsrestformat: 'json',
      username: 'user',
      password: 'pass',
    })
  })
  .then((response) => response.text())
  .then((responseText) => {
    alert(responseText);
  })
  .catch((error) => {
    console.error(error);
  });
}

在浏览器中,这个请求返回一个令牌,但是在我的 react-native android App 中返回一个 xml 错误。

【问题讨论】:

    标签: javascript react-native post request


    【解决方案1】:

    这对我有用

    fetch("http://10.4.5.114/localservice/webservice/rest/server.php", {
      method: 'POST',
      headers: new Headers({
                 'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
        }),
      body: "param1=value1&param2=value2" // <-- Post parameters
    })
    .then((response) => response.text())
    .then((responseText) => {
      alert(responseText);
    })
    .catch((error) => {
        console.error(error);
    });
    

    【讨论】:

    • 以及如何在正文中传递带参数的变量
    【解决方案2】:

    尝试在post请求中添加header。

           headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json',
    
           },
           body: JSON.stringify({
             wstoken: 'any_token',
             wsfunction: 'any_function',
             moodlewsrestformat: 'json',
             username: 'user',
             password: 'pass',
          })
    

    【讨论】:

    • 谢谢,我在向正文添加参数时忘记了 JSON.stringify。
    • 添加json头是更好的解决方案。
    猜你喜欢
    • 2016-07-11
    • 2018-07-15
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2021-12-19
    • 2021-09-24
    • 1970-01-01
    • 2011-12-16
    相关资源
    最近更新 更多