Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 使用react native发出POST请求_Json_React Native_Post_Httprequest - Fatal编程技术网

Json 使用react native发出POST请求

Json 使用react native发出POST请求,json,react-native,post,httprequest,Json,React Native,Post,Httprequest,我正在使用react native开发一个移动应用程序。我对这一点还很陌生,我不知道如何发出正确的POST HTTP请求来向API发送数据。我得到了以下例子: 职位 POST/devapi/records/?access_令牌=[…]HTTP/1.1 主持人:website.org 内容类型:application/x-www-form-urlencoded 单元=12331,标题=测试和日期=2018年10月7日,需求ID=3,isInternal=1,服务类型=校园 成功看起来像: { “

我正在使用react native开发一个移动应用程序。我对这一点还很陌生,我不知道如何发出正确的POST HTTP请求来向API发送数据。我得到了以下例子:

职位

POST/devapi/records/?access_令牌=[…]HTTP/1.1

主持人:website.org

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

单元=12331,标题=测试和日期=2018年10月7日,需求ID=3,isInternal=1,服务类型=校园


成功看起来像:

{

“记录ID”:63, “单位”:2, “姓名”:“鲍勃”, “成功”:真的吗

}


错误如下所示:

{

“消息”:“您必须为此记录输入日期。”, “错误”:-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')
           }
         ],
       );
       }
     });
 }
在测试运行时,my
console.log()
返回:

searchParams units=3&title=test%20测试%20测试和日期=1534402800&requirementId=3&isInternal=0&serviceType=nation


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

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

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

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

但是(无论您是否在RN项目中使用它)建议使用Fetch,使用
方法获取:“POST”
作为字段有时由于某些标题原因不起作用,而且我个人在过去没有将
凭据:“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
库。您需要做的只是:

  • npm在项目文件夹中安装axios
  • 从组件/文件头的“axios”导入axios
  • 在您的项目中使用--我在下面放了一个我使用的片段 发布到域时的其他注意事项是,它允许从此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文件中使用此方法,请确保使用您自己设置的身份验证密钥来保护您的文件

    您应该与后端团队联系。可能您使用了错误的日期参数
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header("Access-Control-Allow-Headers: X-Requested-With");