Network Request Failed with FormData in React Native

Viewed 102

I'm trying to post an item to my server. I'm using React Native for my front end and Laravel as my back-end. I have tried it many times but it keeps giving me Network request failed. Though I am trying it on postman and it works fine.

This is my React-Native code::=>

const { name, price, category_id, description, images } = this.state

const formData = new FormData();
        formData.append('name', name)
        formData.append('price', price)
        formData.append('category_id', category_id)
        formData.append('description', description)
        images.map((image) => {
            var fileURI = image.uri;
            let filename = fileURI.split('/').pop();
            formData.append('images[]', { uri: fileURI, type: image.mime, name: filename });
        })
    
        //FETCH
        const BASE_URL = BASE_URL
        fetch(`http://192.168.8.102:8000/api/items`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
            body: formData
        }).then(response => {
            const statusCode = response.status;
            const responseJson = response.json();
            return Promise.all([statusCode, responseJson]);
        })
            .then(res => {
                const statusCode = res[0];
                const responseJson = res[1];
                if (statusCode == 200) {
                    console.log(responseJson)
                    Alert.alert(
                        'Post successfull',
                        'Thank you for posting, there you go ',
                        [
                            { text: 'not now', style: 'cool', },
                        ],
                        { cancelable: true },
                    );
                    navigation.navigate('DrawerNavigation');
                } else if (statusCode == 422) {
                    Alert.alert('invalid parameters', responseJson.message);
                } else {
                    Alert.alert('account not created', 'something unexpected' + responseJson.message);
                }
            })
            .catch(err => {
                Alert.alert('server error', err.message);
            }).finally(fin => this.setState({ loading: false }))

This is my Laravel code::=>

   $images = $request->file(['images']);
            $image_details = array();

            foreach ($images as $image ) {
                $path = $image->store('public/itemImages');
                $exploded_string = explode("/",$path);
                $image_details[] = new ItemImage (
                [
                    'name' => $exploded_string[2], 
                    'path' => "storage/{$exploded_string[1]}",  
                    'url' => asset("storage/{$exploded_string[1]}/{$exploded_string[2]}")
                ]
             );
            }
0 Answers
Related