【问题标题】:Making a POST request with react native使用本机反应发出 POST 请求
【发布时间】:2018-08-16 02:37:55
【问题描述】:

我正在开发一个带有原生反应的移动应用程序。我对此很陌生,我无法弄清楚如何发出正确的 POST HTTP 请求以将数据发送到 API。我得到了以下示例:

发布https://website.org/api/records/?units=12&title=Volunteering&recordDate=07/10/2018&requirementId=3&serviceType=campus

POST /devapi/records/?access_token=[...] HTTP/1.1

主机:website.org

内容类型:application/x-www-form-urlencoded

units=12331&title=test&date=07/10/2018&requirementId=3&isInternal=1&serviceType=campus


成功的样子:

{

"recordId": 63, “单位”:2, “名称”:“鲍勃”, “成功”:是的

}


错误看起来像:

{

"message": "您必须为此记录输入日期。", “错误”:-2

}

我目前的解决方案如下:

postRecord() {
   const input = {
     units: this.state.units,
     title: this.state.title,
     date: this.convertToUnix(this.state.date),
     requirementId: this.props.navigation.state.params.requirementId,
     isInternal: this.state.differentiateExternal,
     serviceType: this.state.type
   };

   const params = this.props.screenProps.navigation.state.params;
   const accessToken = params ? params.currstate.accessToken : null;
   const searchParams = Object.keys(input).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(input[key])}`).join('&');

   console.log('searchParams', searchParams);

   return fetch('https://webiste.org/devapi/records/?access_token=' + accessToken=[...] HTTP/1.1, {
     method: 'POST',
     header: {
       'Content-length': '86',
       'Content-Type': 'application/x-www-form-urlencoded'
     },
     body: input.units + input.title + input.date + input.requirementId + input.isInternal + input.serviceType
   })
   .then((response) => response.json())
     .then((responseJson) => {
       console.log('the response is:', responseJson);
       if (responseJson.success === 'true') {
         Alert.alert(
          'Record created successfully',
          [
            {
            text: 'Ok',
            style: 'cancel',
            onPress: () => this.props.navigation.navigate('RequirementRecordScreen')
            }
          ]
        );
       } else if (responseJson.error === -2) {
         Alert.alert(
           'There was an error creating the record',
           responseJson.message,
           [
             {
             text: 'Ok',
             style: 'cancel',
             onPress: () => console.log('Cancel xDDDD')
           }
         ],
       );
       }
     });
 }

在测试运行时,我的 console.log() 返回:

searchParams units=3&title=test%20test%20test&date=1534402800&requirementId=3&isInternal=0&serviceType=nation

然后总是返回一个 JSON 响应错误,指出我需要输入多个“单位”。如何修改它以使其正常工作?

【问题讨论】:

  • 您应该联系后端团队。也许您使用了错误的日期参数

标签: json react-native post httprequest


【解决方案1】:

您没有在请求中使用正确的变量

return fetch('https://website.org/devapi/records/?access_token=' + accessToken, {
 method: 'POST',
 header: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 body: searchInput

})

【讨论】:

    【解决方案2】:
     fetch('https://webiste.org/devapi/records/?access_token=' + accessToken=[...] HTTP/1.1',{
      method:'POST',
      headers:{
        'Accept':'application/json',
        'Content-Type':'application/json'
      },
      body: input.units + input.title + input.date + input.requirementId + input.isInternal + input.serviceType
    }).then((response)=>response.json()).
    then((responseJson)=>{    
      if(resppnseJson==='Data Matched')
      {
        alert(responseJson);
      }else{
        alert(responseJson);
      }
    })
    .catch((error)=>{console.error(error)});
    

    你可以通过这种方式发出POST请求

    【讨论】:

      【解决方案3】:

      Expo Documentation(无论您是否将它用于您的 RN 项目)建议使用 Fetch,但是,以 method: 'POST' 作为字段的 Fetch 有时由于某些标题原因不起作用,我个人有过去当我不输入 credentials: 'include' 作为参数时,它的错误。

      axios.post(url, { userData: JSON.stringify(userData), oauth_provider:"google" })
      .then(response => { 
          console.log("POST RESPONSE: " , JSON.stringify(response));
          // alert(JSON.stringify(response))
      })
      .catch(error => {
          console.log("ERROR RESPONSE: " , JSON.stringify(error));
      });
      

      我建议使用axios 库。您需要做的就是:

      1. npm install axios 在您的项目文件夹中
      2. import axios from "axios" 在组件/文件的标题中
      3. 在您的项目中使用 -- 我在下面放了一个我使用的 sn-p。

      发布到域时的其他注意事项是它允许从该 URL 访问,如果您要发布到 API,则在 PHP 文件的顶部使用这些标头。

      header('Access-Control-Allow-Origin: *');
      header('Access-Control-Allow-Methods: GET, POST');
      header("Access-Control-Allow-Headers: X-Requested-With");
      

      * 可以替换为您的 URL 名称。如果您确实在 PHP 文件中使用此方法,请务必使用您自己设置的身份验证密钥来保护您的文件。

      【讨论】:

        猜你喜欢
        • 2021-12-25
        • 2019-08-02
        • 2017-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        • 2017-06-02
        • 2021-05-18
        相关资源
        最近更新 更多