I have want to upload an image but I seem to be getting network request error.
sample values
{"name": "IMG20200427083924.jpg", "type": "image/jpeg", "uri": "content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F240735/ORIGINAL/NONE/image%2Fjpeg/158476572"}.
Am I doing this right?
export const uploadDocumentAction = (profpic) => {
console.log(Endpoint.UPLOAD_DOCUMENT_URL)
return async (dispatch) => {
dispatch(uploadDocument());
try {
let body = new FormData();
body.append('document', { uri: profpic.uri, name: profpic.filename, type: profpic.type });
await AsyncStorage.getItem('accessToken', (error, accessToken) => {
fetch(Endpoint.UPLOAD_DOCUMENT_URL, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${accessToken}`
},
body: body
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
dispatch(uploadDocumentSuccess(responseJson));
})
.catch((error) => {
console.log('error', error);
dispatch(uploadDocumentFailed())
})
});
} catch (error) {
console.log(error);
dispatch(uploadDocumentFailed('Internal Server Error'))
}
}
}
Related
I list some room_name from the backend with React.js
What I want to implement is that user can delete room_name when user clicks the trash can icon.
Issue/error message
Request failed with status code 422
It's strange
As shown in the picture, I can see "the body sent to server section" on the console.
I can confirm that the room_name has been sent properly.
I believe the data you are sending is correct.
Even if I try with Postman with the same URL and data, I can delete it successfully.
const SettingGetRoomName = () => {
const [room_name, setRoomName] = useState([]);
const DeleteRoom = async(data) => {
console.log("Body sent to server", {
home_rooms: [data.item],
})
await axios.delete("xxx.com",
{
home_rooms: [data.item],
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
alert('Succeded delete room!');
console.log('Succeded delete room!');
})
.catch(err => {
alert('Missed delete room!');
console.log(err);
console.log('Missed delete room!');
});
}
const getRoomName = async(data) => {
await axios.get("xxx.com",
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
setRoomName(result.data.home_rooms);
})
.catch(err => {
console.log(err);
});
}
useEffect(() => {
getRoomName();
},[]);
return (
<>
{room_name.map((item,i) =>
<div key={i} className="flex_setting_get_room_box">
<div className="my_hubs">
<p className="">{item}</p>
<img src={ic_delete} onClick={(e)=>DeleteRoom({item})}/>
</div>
</div>
)}
</>
);
}
export default SettingGetRoomName;
Check this link and the axios docs. The second parameter of axios.delete() is not the request body, but rather the request options. Simply add the body on the data key of the request options:
await axios.delete("xxx.com", {
data: {
home_rooms: [data.item]
},
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
alert('Succeded delete room!');
console.log('Succeded delete room!');
})
.catch(err => {
alert('Missed delete room!');
console.log(err);
console.log('Missed delete room!');
});
I am trying to send an object from react to express server using node.js
this is my object:
const formData = {
location: location,
cost: cost,
email: email,
image: image,
};
This is my fetch post method :
fetch("http://localhost:5000/places", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(formData),
})
.then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
I can see the image file object in client site console but I am not getting that in expreess server.
You have to send your input data as FormData to share images/files to the backend.
function uploadImage() {
let formData = new FormData(yourFormData);
fetch("http://localhost:5000/places", {
method: "POST",
body: formData,
}).then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
}
I am trying to add a user to a group with a axios patch request. the data is all correct but i get a 401 error even though i include the Authorization in the header. Code is below any help is greatly appreciated.
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://localhost:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://localhost:8000/core/usergroup/${user.data.id}/`, {
group_data,
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Edit: Attempting to rewrite the request and changing the position of the group_data variable stops the 401 error but does not change the data in the model.
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://localhost:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://localhost:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Edit:
I changed the handler and now it is updating the group field but completely overwriting it. When i try to send group as a list it gives error expecting a int that represents pk. So my question is, is there a method to patch the model without overwriting the previous information.
Handler with group value as id
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
let group_data = new FormData();
group_data.append('user', user.data.id);
group_data.append('group', group.id);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
Handler with group as list
handleJoin = (e, group) => {
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then((user) => {
axios.get(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
}
})
.then((usergroup) => {
let group_data = new FormData();
let prev = usergroup.data.group
prev.push(group.id);
console.log(prev);
group_data.append('user', user.data.id);
group_data.append('group', prev);
for (var value of group_data.values()) {
console.log(value);
}
axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
})
})
.catch((err) => {
console.log(err);
});
}
The backend is written with Django and i realize the problem may be there instead of the front end. I am also posting my serializer and views in case they may be the problem. Any help would be really appreciated.
Serializer
class UserGroupSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True, read_only=True,)
class Meta:
model = UserGroup
fields = '__all__'
View
class UserGroupDetail(APIView):
def patch(self, request, pk):
usergroup = UserGroup.objects.get(pk=pk)
serializer = UserGroupSerializer(instance=usergroup, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Your authorization header should be
Authorization: `Bearer ${localStorage.getItem('token')}`
I want to make a post request to backend with all form data.
Uploading the images i get an array with data:
const normFile = e => {
const getFileList = e.fileList.map( i => i.originFileObj);
console.log('Upload event:', getFileList);
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ images: getFileList })
})
.then(async response => {
const data = await response.json();
console.log(data, 'res data')
})
.catch(error => {
console.error('There was an error!', error);
});
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
Above is my code where i use Ant Design uploader.
But how to delete the File text before each object?
You have to use multipart/form-data header
Let's say you have an input
<input type="file" onChange={uploadFile}/>
And logical part:
uploadFile = (e) => {
const formData = new FormData();
formData.append('name_your_file', e.target.files[0])
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
})
}
I'm trying to refresh some data when users re-vistis the screen. The way im using other places and it works. but can't figure out why this won't fly on this screen?
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this.handleDidFocus)
}
async handleDidFocus() {
...
}
This is how I load data the first time and want to load it again when users revisits.
componentWillMount() {
this.getGroupAccepted();
}
async getGroupAccepted() {
if (this.state.token == null) {
var token = await AsyncStorage.getItem("token");
this.setState({ "token": token });
}
fetch('https://.../api/group/getActive', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: this.state.token
})
})
.then(response => response.json())
.then((data) => {
this.setState({
groups_accepted: data.groups_active,
loading: false,
});
})
.catch((error) => {
console.error(error);
});
}
This is what worked. Now when a user revisits the screen it loads the data once again.
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this._handleDataChange)
}
_handleDataChange = () => {
this.getGroupAccepted();
}