- SDK Version:43
- Platforms(Android/iOS): Android
- Add the appropriate “Tag” based on what Expo library you have a question on.
I am trying to post images to mongo db using expo react native using expo image picker library and formdata but some how I get network request failed error using fetch and some object syntax error if i try to use axios.However my project works fine using post man.Thanks
Here is the code
import {
View,
Text,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
ScrollView,
Picker,
Platform,
Alert,
input,
KeyboardAvoidingView
//fetch
} from "react-native";
import mime from "mime";
import React, { Component } from "react";
import axios from "axios";
import * as ImagePicker from 'expo-image-picker';
import Constants from "expo-constants";
import * as FileSystem from 'expo-file-system';
import QueryString from "qs";
export default class Sellnow extends Component {
constructor(props) {
super(props);
this.onChangePetName = this.onChangePetName.bind(this);
this.onChangePetTitle = this.onChangePetTitle.bind(this);
this.onChangePetContact = this.onChangePetContact.bind(this);
this.onChangePetPrice = this.onChangePetPrice.bind(this);
this.onChangePetDescription = this.onChangePetDescription.bind(this);
this.onValueChangeCat= this.onValueChangeCat.bind(this);
this.onValueChangeCity= this.onValueChangeCity.bind(this);
this.onFileChange = this.onFileChange.bind(this);
// this.pickImage = this.pickImage.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// State
this.state = {
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat:"",
selectedcity:"",
imgforsell:"",
//collection categories
category: [
{
itemName: "Select Category...."
},
{
itemName: "Pets Food"
},
{
itemName: "Pets Products"
},
{
itemName: "Pets Accessories"
}
],
// cities category
cityCategory:[
{
itemName: "Select City...."
},
{
itemName: "Islamabad"
},
{
itemName: "Rawalpindi"
},
{
itemName: "Lahore"
},
{
itemName: "Peshawar"
},
{
itemName: "Karachi"
},
{
itemName: "Quetta"
}
]
};
}
onChangePetName(e) {
this.setState({ name: e.target.value });
}
onChangePetTitle(e) {
this.setState({ title: e.target.value });
}
onChangePetContact(e) {
this.setState({ contact: e.target.value });
}
onChangePetPrice(e) {
this.setState({ price: e.target.value });
}
onChangePetDescription(e) {
this.setState({ description: e.target.value });
}
// categories function
onValueChangeCat(e) {
this.setState({ selectedcat: e.targetvalue })
}
// city function
onValueChangeCity(e) {
this.setState({ selectedcity: e.targetvalue })
}
onFileChange(e) {
this.setState({ imgforsell: e.targetvalue})}
// uploading Image
_getPhotoLibrary = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
base64: true,
exif: true,
aspect: [4, 3]
});
if (!result.cancelled) {
this.setState({ imgforsell: result });
}
this.props.navigation.setParams({
imgforsell: this.state.imgforsell
});
};
async onSubmit() {
// e.preventDefault();
//const formData = new FormData();
const FormData = global.FormData;
const formData = new FormData();
//formData.append("name", this.state.name);
formData.append("name",name);
//formData.append("title", this.state.title);
formData.append("title", title);
//formData.append("contact", this.state.contact);
formData.append("contact", contact);
//formData.append("price", this.state.price);
formData.append("price", price);
// formData.append("description", this.state.description);
formData.append("description", description);
// formData.append("selectedcat", this.state.selectedcat);
formData.append("selectedcat", selectedcat);
// formData.append("selectedcity", this.state.selectedcity);
formData.append("selectedcity", selectedcity);
formData.append("imgforsell", {
uri:imgforsell.uri,
type:imgforsell.type
});
// formData.append("imgforsell",imgforsell)
// from stack overflow
fetch(
`"http://${
Platform.OS === "android" ? " 192.168.88.45" : "localhost"
}:4040/pets/addpets"`,
formData,
//'http://10.0.2.2:4040/pets/addpets/',
//formData,
{
method: 'POST',
//body: JSON.stringify(formData),
// body:formData,
mode: 'cors',
headers: {
//Accept: 'application/json',
"content-Type": `multipart/form-data; boundary={formData._boundary}`,
},
body:QueryString.stringify(formData)
// headers:{"Content-type":"application/json"}
}
)
.then((res) => {
if (!res.ok) {
return Promise.reject(res);
}
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});
/*
await axios
.post(
`https://${
Platform.OS === "android" ? "192.168.88.45" : "localhost"
}:4040/pets/addpets`,
QueryString.stringify(formData),
{
headers: {
//'Content-Type': 'multipart/form-data; boundary=${formData._boundary}',
"Content-Type": "application/x-www-form-urlencoded"
},
//transformRequest: (formData,headers) => {
//return formData; // this is doing the trick
//},
},
//{ transformRequest: [
// function(formData, headers) {
// headers["Content-Type"] = `application/json ; boundary=${formData._boundary}`;
//return JSON.stringify(formData);
//}
// ]
}
)
.then(res => {
console.log('Data Posted',res);
})
//})
.catch((err) => {
console.error(err.toJSON());
// res.status(500).json(err) 👈 don't do this, it's not Express
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});*/
}
render() {
const {imgforsell} = this.state
return (
<View>
<ScrollView
nestedScrollEnabled={true}
showsVerticalScrollIndicator={false}
>
<View style={styles.container}>
<View style={styles.formContainer}>
<Text style={styles.conText}>Please Fill the Below Form </Text>
<View style={styles.borderForm}>
<Text style={styles.formText}>Your Name</Text>
<TextInput
style={styles.formInput}
multiline
placeholder="Please Enter Your Name"
maxLength={15}
value={this.state.name}
onChange={this.onChangePetName}
blurOnSubmit={true}
onChangeText={(name) => this.setState({ name })}
/>
<Text style={styles.formText}>Category</Text>
{ /*<CategoryDropList />*/ }
<View style={styles.viewStyle}>
<Picker
itemStyle={styles.itemStyle}
mode="dropdown"
style={styles.pickerStyle}
selectedValue={this.state.selectedcat}
// onValueChange={this.onValueChangeCat.bind(this)}
//onValueChange={(selectedcat)=>this.setState({selectedcat})}
onValueChange={(itemValue,itemIndex)=> this.setState({selectedcat:itemValue})}
>
{this.state.category.map((item, index) => (
<Picker.Item
color="black"
label={item.itemName}
value={item.itemName}
index={index}
/>
))}
</Picker>
</View>
<Text style={styles.formText}>Pet/Product Title</Text>
<TextInput
style={styles.formInput}
placeholder="Enter Product Title"
maxLength={15}
value={this.state.title}
blurOnSubmit={true}
onChange={this.onChangePetTitle}
onChangeText={(title) => this.setState({ title })}
/>
<Text style={styles.formText}>City</Text>
{/*<CityDropList />*/}
<View style={styles.viewStyle}>
<Picker
itemStyle={styles.itemStyle}
mode="dropdown"
style={styles.pickerStyle}
selectedValue={this.state.selectedcity}
onValueChange={(itemValue,itemIndex)=> this.setState({selectedcity:itemValue})}
>
{this.state.cityCategory.map((item, index) => (
<Picker.Item
color="black"
label={item.itemName}
value={item.itemName}
index={index}
/>
))}
</Picker>
</View>
<Text style={styles.formText}> Contact Number </Text>
<TextInput
style={styles.formInput}
placeholder="Phone Number"
inputType="number"
maxLength={11}
keyboardType="number-pad"
blurOnSubmit={true}
value={this.state.contact}
onChange={this.onChangePetContact}
onChangeText={(contact) => this.setState({ contact })}
/>
<Text style={styles.formText}>Price</Text>
<TextInput
style={styles.formInput}
multiline
placeholder="Enter Price"
inputType="number"
keyboardType="number-pad"
blurOnSubmit={true}
maxLength={7}
value={this.state.price}
onChange={this.onChangePetPrice}
onChangeText={(price) => this.setState({ price })}
/>
<Text style={styles.formText}>Image of Product</Text>
{/*<ImagePickerExample />*/}
<TouchableOpacity style={styles.btn} onPress={this._getPhotoLibrary.bind(this)}>
<Text style={styles.btnTxt}> Choose File</Text>
</TouchableOpacity>
{imgforsell ? (
<Image source={{ uri: imgforsell.uri }} style={styles.uploadimgstyle} />
) : (
<View/>
)}
<Text style={styles.formText}>
Description(Optional max 150 words)
</Text>
<TextInput
style={styles.descriptionInput}
multiline
placeholder="Describe your product"
maxLength={150}
blurOnSubmit={true}
value={this.state.description}
onChange={this.onChangePetDescription}
onChangeText={(description) => this.setState({ description })}
/>
<TouchableOpacity style={styles.btn} onPress={this.onSubmit}>
<Text style={styles.btnTxt}>Submit</Text>
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
</View>
);
}
}
Here is error using fetch:
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:123:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:379:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue
Here is error using axios:
Object {
"code": undefined,
"columnNumber": undefined,
"config": Object {
"adapter": [Function xhrAdapter],
"data": "{\"_parts\":[[\"name\",\"Bebswb\"],[\"title\",\"Bssbbs\"],[\"contact\",\"12345688770\"],[\"price\",\"5588888\"],[\"description\",\"Vvvvvvv\"],[\"selectedcat\",\"Pets Food\"],[\"selectedcity\",\"Peshawar\"],[\"imgforsell\",{\"cancelled\":false,\"width\":2160,\"exif\":{\"DateTime\":\"2015:11:04 17:32:48\",\"Software\":\"Adobe Photoshop CC (Windows)\",\"XResolution\":72,\"ImageWidth\":2160,\"Orientation\":0,\"ImageLength\":1620,\"ResolutionUnit\":2,\"LightSource\":0,\"ColorSpace\":1,\"JPEGInterchangeFormat\":302,\"YResolution\":72,\"Compression\":6,\"JPEGInterchangeFormatLength\":5674},\"height\":1620,\"base64\":\"/9j/4QG+RXhpZgAATU0AKgAAAAgADAESAAQAAAABAAAAAAEAAAQAAAABAAAIcAEaAAUAAAABAAAAngExAAIAAAAdAAAApgICAAQAAAABAAAWKodpAAQAAAABAAAA3wEDAAMAAAABAAYAAAEbAAUAAAABAAAAwwEBAAQAAAABAAAGVAEyAAIAAAAUAAAAywEoAAMAAAABAAIAAAIBAAQAAAABAAABLgAAAAAACvyAAAAnEEFkb2JlIFBob3Rvc2hvcCBDQyAoV2luZG93cykAAAr8gAAAJxAyMDE1OjExOjA0IDE3OjMyOjQ4AAACkggAAwAAAAEAAAAAoAEAAwAAAAEAAQAAAAAAAAAIARoABQAAAAEAAAFjATEAAgAAAB0AAAFrAgIABAAAAAEAABYqAQMAAwAAAAEABgAAARsABQAAAAEAAAGIATIAAgAAABQAAAGQASgAAwAAAAEAAgAAAgEABAAAAAEAAAEuAAAAAAAK/IAAACcQQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKQAACvyAAAAnEDIwMTU6MTE6MDQgMTc6MzI6NDgAAAEANwADAAAAAQABAAAAAAAA/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/9sAQwEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/8AAEQgGVAhwAwEiAAIRAQMRAf/EAB8AAAE