使用本机发出POST请求

时间:2018-08-16 02:37:56

标签: json react-native post httprequest

我正在使用具有本机响应的移动应用程序。我对此很陌生,无法解决如何发出适当的POST HTTP请求以将数据发送到API的问题。给出了以下示例:

POST 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   “ name”:“ Bob”,   “成功”:是

}


错误看起来像:

{

“消息”:“您必须输入该记录的日期。”,   “错误”:-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单位= 3&title = test%20test%20test&date = 1534402800&requirementId = 3&isInternal = 0&serviceType = nation

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

3 个答案:

答案 0 :(得分:0)

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

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

})

答案 1 :(得分:0)

 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请求

答案 2 :(得分:0)

Expo Documentation(无论您是否在RN项目中使用它)都建议使用Fetch,但是,由于某些标头原因,使用method: 'POST'作为字段的F有时不起作用,并且过去,当我不输入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. 在您的项目中使用-我在下面放了一个代码段。

发布到域时的其他注意事项是它允许从此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文件中使用此方法,请确保使用您自行设置的身份验证密钥来保护文件。