繁体   English   中英

如何在获取请求中传递 POST 参数? - 反应本机

[英]How can I pass POST parameters in fetch request? - React Native

这是我的代码:

componentWillMount() {
  fetch("http://10.4.5.114/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 应用程序中返回一个 xml 错误。

这对我有用

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);
});

尝试在发布请求中添加标头。

       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',

       },
       body: JSON.stringify({
         wstoken: 'any_token',
         wsfunction: 'any_function',
         moodlewsrestformat: 'json',
         username: 'user',
         password: 'pass',
      })

您是否尝试过指定内容类型?

https://facebook.github.io/react-native/docs/network.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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