React native Axios or fetch when i called post method (get method working fine) post parameters are getting null data on server side

≡放荡痞女 提交于 2021-01-29 09:41:09

问题


When called the post method getting null parameters on the server-side (PHP - Codeigniter). When I used JSON.stringify it is working but on the server-side, I have to handle the request with the payload ( $request_body = file_get_contents('php://input')) as of now is fine, Problem is when I am trying to upload a file (Video/ Image) , Payload won't support. So If I am using the form data it is throwing network error it means Axios did not even go to the server. I have tested the same service from javascript,php, and postman all are working fine only react-native call failing So what is the solution it's been 3 days I am trying for this by changing the header content is a different way still not able to understand.

Following code given below

   // alert('check ');
    // const res = DocumentPicker.pick({
    //     type: [DocumentPicker.types.allFiles],
    // }).catch(error => {
    //     alert('doct' + error);
    // });
    //Printing the log realted to the file  
    const imageUrl = 'https://image.shutterstock.com/image-photo/floral-spring-natural-landscape-wild-260nw-1274207287.jpg';
    // if (true) {
    // const fileToUpload = res;
    const formData = new FormData();
    formData.append('name', 'Image Upload');
    formData.append('file_attachment', {
        uri: imageUrl,
        type: "image/jpg",
        name: 'floral-spring-natural-landscape-wild-260nw-1274207287.jpg'
    });
    Axios({
        url: URL + '/VideosController/upload',
        method: 'POST',
        data: formData,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data'
        },
    }).then(
        response => {
            alert('res' + JSON.stringify(response.data));
        },
        error => {
            alert('check+ ' + error);
        })
        .catch(error => {
            alert('No error' + error);
        });

Server-side PHP code

header("Access-Control-Allow-Methods: GET,POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
// By searching i seen it might cors error so added headers on top of my method no use



  if(!empty($_FILES['file_attachment']['name'])) {
    $res        = array();
    $name       = 'file_attachment';
    $imagePath  = 'assets/upload/file_attachment';
    $temp       = explode(".",$_FILES['file_attachment']['name']);
    $extension  = end($temp);
    $filenew    = str_replace($_FILES['file_attachment']['name'],$name,$_FILES['file_attachment']['name']).'_'.time().''. "." .$extension;          
    $config['file_name']   = $filenew;
    $config['upload_path'] = $imagePath;
   
    $this->upload->initialize($config);
    $this->upload->set_allowed_types('*');
     print_r($_FILES);
    exit;
    $this->upload->set_filename($config['upload_path'],$filenew);
    
    if(!$this->upload->do_upload('file_attachment')) {
      $data = array('msg' => $this->upload->display_errors());
    } else {
      $data = $this->upload->data();    
      if(!empty($data['file_name'])){
        $res['url'] = 'assets/upload/file_attachment/'.$data['file_name']; 
      }
      if (!empty($res)) {
    echo json_encode(array("status" => 1, "data" => array() ,"msg" => 'upload successfully', 'base_url' => base_url(), "count" => '0'));
      }else{
    echo json_encode(array("status" => 1,"data" => array() ,"msg" => 'not found', 'base_url' => base_url(), "count" => '0'));
      }
    }
  }

Error when i am using formdData:

error = Error: Network Error at createError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:155044:17) at EventTarget.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:154946:16) at EventTarget.dispatchEvent (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:34135:27) at EventTarget.setReadyState (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:33219:20) at EventTarget.__didCompleteResponse (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:33046:16) at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:33156:47 at RCTDeviceEventEmitter.emit (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3422:37) at MessageQueue.__callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2750:44) at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2472:17 at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2704:13)

Please explain the subject of what is actually happening and the solution.


回答1:


The first thing you need to upsize the payload limit on server-side, still cause a problem then mention the details.




回答2:


Finally, I found the solution by upgrading the FLIPPER_VERSION to 0.41.0 this issue gets resolved but If I upgraded the app not even opening for me. So for now what I did is in the below file I just commented on these lines. worked for me.

\android\app\src\debug\java\com\appname\ReactNativeFlipper.java

public void apply(OkHttpClient.Builder builder) {
            //  builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
            }

I just commented this line for more assistance you can check the below link

URL: https://github.com/facebook/react-native/issues/28551#issuecomment-656601532

If you wanna update flipper version it will be available at ..\android\gradle.properties



来源:https://stackoverflow.com/questions/62787875/react-native-axios-or-fetch-when-i-called-post-method-get-method-working-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!