1

I am uploading an image using react-native and my API is PHP based. When I test my API using Post Man it works correctly but when I pass an image from the react-native app it shows me an error-

SyntaxError: JSON Parse error: Unexpected end of input

Here is the code for sending an image using the POST method at the react-native side-

uploadImageToServer = () => {

    const data = new FormData();
        data.append('image', {
          name: this.state.name, // rn_image_picker_lib_temp_b9855c66-9093-433e-af06-475ef6e82a3f.jpg
          type: this.state.type, // image/jpeg
          uri: this.state.uri, // file:///data/user/0/com.tmbs_ekta/cache/rn_image_picker_lib_temp_b9855c66-9093-433e-af06-475ef6e82a3f.jpg
     });

    fetch('https://tmbsbavan.com/api/family_method.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      body: data,
    }).then((response) => response.json())
    .then((json) => {
      console.log(json);

    }).catch((err) => { console.log(err); });
 
  }

Server-side PHP code-

<?php
    $target_dir = "profile_pic";
    $target_dir = '../'.$target_dir . "/" .rand() . "_" . time() . ".jpeg";
    
    if(move_uploaded_file($_FILES['image']['tmp_name'], $target_dir)){
        $MESSAGE = "Image Uploaded Successfully." ;
        echo json_encode($MESSAGE);
    }
?>

Please help me with how can I solve this issue. In Postman the API is working properly but in react native. it's showing an error.

4
  • When i am using a postman, image get uploaded successfully to the server. but when I call API in react native. image can't upload Commented Dec 1, 2022 at 14:33
  • nothing was happen, getting same issue in React native Commented Dec 1, 2022 at 14:56
  • Are you developing with Android? And one of the debug method is check any error returned by the PHP server, use .then((response) => response.text()) to check that. Commented Dec 2, 2022 at 1:15
  • Thanks a lot sir @PeterTam this is will be help me for finding serverside error response Commented Dec 4, 2022 at 5:32

1 Answer 1

1

An unconfigured cors may be the problem

<?php
header("Access-Control-Allow-Origin: *");
Sign up to request clarification or add additional context in comments.

1 Comment

Okky, you save my day. thank you....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.