FormData POST request throws Network error

南笙酒味 提交于 2020-01-03 18:45:08

问题


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

来源:https://stackoverflow.com/questions/52872893/formdata-post-request-throws-network-error

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