简体   繁体   English

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

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

This is my code:这是我的代码:

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

In the browser, this request returns a token, but in my react-native android App returns a xml error.在浏览器中,此请求返回一个令牌,但在我的 react-native android 应用程序中返回一个 xml 错误。

This what worked for me这对我有用

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

Try to add header in post request.尝试在发布请求中添加标头。

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

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

Have you tried specifying the Content-Type? 您是否尝试过指定内容类型?

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

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

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