FormData POST request throws Network error

2019-07-31 06:10发布

问题:

I have a react native app that allows users to upload images to the server along with additional data.

I'm using NodeJS and ExpressJS as my backend framework. The route for posting images:

router.post("/", checkAuth, upload.single("gallery_item_image"), function (req, res, next) {
Branch
    .findById({ _id: req.body.branch_id })
    .exec()
    .then((doc) => {
        if(!doc) {
            return res.status(404).json({
                message: "Invalid Branch ID",
            })
        }
        galleryItem = new GalleryItem({
            _id: mongoose.Types.ObjectId(),
            branch_id: req.body.branch_id,
            caption: req.body.caption,
            description: req.body.description,
            imageUrl: "https://someurl.com/" + req.file.filename,
            imageId: req.file.id,
        })
        return galleryItem.save()
    })
    .then((response) => {
            console.log(response);
            res.status(201).json({
                message: "Gallery item successfully added to the database",
                galleryItem: {
                    _id: response._id, 
                    branch_id: response.branch_id, 
                    caption: response.caption, 
                    description: response.description, 
                    date: response.date,
                    imageUrl: response.imageUrl,
                    imageId: response.imageId,
                    meta: {
                        type: "GET", 
                        url: "https://someurl.com/" + response._id,
                    }
                }
            })
        })
    .catch((error) => {
        console.log(error);
        res.status(500).json({
            error: error
        })
    })

})

I'm using axios to make ajax calls and the function that is making these calls looks like this:

submit = async() => {

    if(this.state.imagePicked && this.state.title.length > 0 && this.state.description.length > 0) {

        this.setState({
            isLoading: true
        })

        try {

            console.log(`submit()----> getting user data from AsyncStorage...`)
            let data = await AsyncStorage.getItem(CONSTANTS.ASYNC_STORAGE.USER)
            data = JSON.parse(data)
            console.log(`submit()----> user received from AsyncStorage: ${JSON.stringify(data)}`)

            const formData = new FormData();
            formData.append('gallery_item_image', this.state.imageData);
            formData.append("branch_id", data.branchId)
            formData.append("caption", this.state.title)
            formData.append("description", this.state.description)
            let apiResponse = await axios({
                method: 'post',
                url: CONSTANTS.API.GALLERY,
                data: formData,
                config: {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            })
            let apiResponseJson = await apiResponse.json()
            console.log(`submit()----> axios response: ${JSON.stringify(apiResponseJson)}`)
            // const config = {
            //     method: 'POST',
            //     headers: {
            //         Authorization: data.authToken, 
            //         'Content-Type': 'multipart/form-data'
            //     },
            //     body: formData,
            // };

            // console.log(`submit()----> posting data to API: ${JSON.stringify(formData)}`)
            // try {
            //     let response = await fetch(CONSTANTS.API.GALLERY, config) 
            //     console.log(`submit()----> response from API: ${JSON.stringify(response)}`)
            //     this.setState({
            //         isLoading: false,
            //         isModalVisible: false
            //     })
            // } catch(error) {
            //     console.log(`submit()----> error occured when posting data to API: ${error}`)
            //     this.setState({
            //         isLoading: false, 
            //         error: true, 
            //         errorMessage: `error occured when posting data to API: ${error}`
            //     })
            //     return;
            // }
            this.setState({
                isLoading: false
            })

        } catch(error) {

            console.log(`submit()----> error occured when getting data from AsyncStorage: ${error}`)

            this.setState({
                isLoading: false, 
                error: true, 
                errorMessage: error
            })
            return;

        }

        return;

    } else {

        console.log(`submit()----> empty field found`)
        return; 

    }

    return;
}

However, I always get "Network Error" without any explanation.

console output Application output