React Native中的FormData网络请求失败

时间:2020-09-30 15:38:03

标签: javascript php laravel react-native

我正在尝试将项目发布到我的服务器上。我将React Native用作前端,将Laravel用作后端。我已经尝试了很多次,但是它一直在给我网络请求失败。虽然我在邮递员上尝试,但效果很好。

这是我的React-Native代码:: =>

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 }))

这是我的Laravel代码:: =>

   $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 个答案:

没有答案