【问题标题】:Sending an array to a server to fetch some data with React Native使用 React Native 将数组发送到服务器以获取一些数据
【发布时间】:2018-05-03 13:27:41
【问题描述】:

我正在尝试使用给定数据从服务器获取数据。我正在使用以下代码:

    const details = {
      'function': 'getUsers',
    };
    const formBody = 
    Object.keys(details).map(key=>encodeURIComponent(key)+
    '='+encodeURIComponent(details[key])).join('&');
    console.log(formBody);
    fetch(url, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'XPIDER_SID=' + this.props.text
      },
      body: formBody
      }).then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.status === 'okay') {
            this.setState({ users: responseJson.users });
          } else {
             this.setState({ error: responseJson.error });
          }
      })

直到现在它都很好用。现在我必须发送一个数据数组,但是当我在 details 常量中写入一个数组时,由于 formBody 的原因,服务器不会获取该数组。在formBody中,整个请求都是字符串,所以数组转换成字符串。我怎样才能用这个发送一个数组?或者你们知道其他选择吗?谢谢!

【问题讨论】:

  • 我认为你可以在请求中使用data参数

标签: arrays api react-native http-post fetch-api


【解决方案1】:

像这样以 JSON 格式发送您的数组:

body: JSON.stringify(your_array)

然后在服务器上反序列化

【讨论】:

  • 感谢您的回答。但我不能发送 JSON,因为格式必须是 x-www-form-urlencoded
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
相关资源
最近更新 更多