I want to upload a file using Axios but for that I need to use formData, my problem is that when I am using formData the data are not send at all.
Here is my code without formData, its working fine all the data are sent :
axios({
method: 'post',
url: jsonurl,
data: {
session_id: '123',
},
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 and config: data: session_id: "123" ...
})
.catch(err=>console.error(err));
Same code with formData (no data sent, $_GET['id'] doesnt exist) :
const formData = new FormData();
formData.append('session_id', '123');
axios({
method: 'post',
url: jsonurl,
formData,
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 but config: data: FormData {}
})
.catch(err=>console.error(err));
No data sent, return in console status 200 but config: data: FormData {} (so no data) and on backend $_POST['session_id'] doesnt exist, the form is sent (I get my jsonencode return) but there is no input data.
I dont catch any error either.
Finally I found the solution, my syntax was wrong, here is one who works :
var postResults = await axios.post(jsonurl,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function(value){
console.log(value);
return value;
})
.catch(function(error){
console.log(error);
});
Related
const availabilityData = new FormData();
availabilityData.append('name', title);
availabilityData.append('foodType', foodType);
availabilityData.append('availability_type', category);
availabilityData.append('description', description);
availabilityData.append('total_quantity', quantity);
availabilityData.append('cooked_time', madeOn);
availabilityData.append('best_before', bestBefore);
availabilityData.append('storage_description', storageDesc);
availabilityData.append('latitude', fromLocation.latitude);
availabilityData.append('longitude', fromLocation.longitude);
availabilityData.append('city', selectedCity);
availabilityData.append('creator_delivery_option', deliveryOption);
for (let i = 0; i < imageLoc.length; i++) {
const newFile = {
uri: imageLoc[i],
type: 'image/jpg',
name: new Date(),
};
availabilityData.append('files[]', newFile);
}
await axios({
url: constants.BASE_URL + 'availability/createAvailability',
method: 'post',
data: availabilityData,
headers: {
Authorization: `UserData ${token}`,
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
})
.then(function (response) {
Alert.alert('Availability Created Successfully');
navigation.popToTop();
removeAllInputs();
setLoading(false);
})
.catch(function (error) {
console.log(error);
setLoading(false);
});
}
imageLoc is the State where I have stored the location of selected Images.
output when I print imageLoc:
["content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151358739.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151913720.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-15253326.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-152139570.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-1524187.jpg"]
Error I got in the backend
You are having Content-Provider paths in your file array. A content provider is not a valid url in Android and probably Axios is not prepared to handle them. In this case you can copy the files for example with react-native-fs to a different location:
RNFS.copyFile(uri, targetPath)
And then provide the targetPath to axios. Make sure to delete the copies after sending the images.
I'm trying send a post request using axios to my backend but I can't send the boolean "isActive" for some reason. Is there a way to do this?
async submit() {
const isValid = await this.$validator.validateAll()
if (isValid && !this.submitting) {
let formData = new FormData();
formData.set("city", this.formData.city)
formData.set("state", this.formData.state)
formData.set("county", this.formData.county)
formData.set("isActive", true) // <- NOT ACCEPTING THIS VALUE
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.status === 200) {
this.submitting = true
this.cancelModal()
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
}
FormData can only contain string values. Setting a Boolean true would result in "true" for the value. The backend would have to convert that string to a Boolean.
Also, your header should not be application/json (intended for JSON payloads). If sending FormData as the payload, the header should be multipart/form-data:
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
If your backend is actually expecting JSON, then you can't send FormData. Switch to a JavaScript object instead (which does accept Booleans):
const payload = {
city: this.formData.city,
state: this.formData.state,
county: this.formData.county,
isActive: true,
}
axios.post("/api/v1/team/createTeam", payload, {
headers: {
'Content-Type': 'application/json'
}
})
I try to send my Image from react-native to my database.
it sends my image's base64 code. However, base64 code is too long so my webservice doesnt take all of them. How can I send it ?
This is what I tried :
selectPhoto = () => {
const options = {};
ImagePicker.showImagePicker(options, response => {
if (response.uri) {
this.setState({ data: response.data });
}
});
}
sendImage() {
fetch('url', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify(this.state.data), // data has base64 code
})
}
I am waiting for successful JSON from server:
{"...."}
Actual Behavior
I get
SyntaxError: Unexpected token b in JSON at position 0
b is the first letter of word "badlogin". It responds server when sent wrong combination of userName and password. But when I use Postman with the same key values combination on the same address I get correct rosponse from the server.
Steps to Reproduce
fetch('http://....', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userName: "react",
password: "123",
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.message);
if(responseJson.success === true) {
alert('successufuly loged');
}
else{
console.log(responseJson.message);
alert(responseJson.message);
}
})
}
}
You are trying to parse a string. This is the error. Instead of always parse the json, just add a clausule to check if the request was made with success
}).then((response) => {
if(!response.ok) {
// handle your error here and return to avoid to parse the string
return
}
return response.json()
})
.then()
Look like the response you got is not json
Try to check what is the response you are getting first:
.then((response) => response.text())
.then((responseJson) => {
console.log(responseJson);
}
I solved this issue by using FormData to prepare data for sending:
......
login = () => {
var formData = new FormData();
formData.append('username', 'react');
formData.append('password', '123');
fetch('http://......', {
method: 'POST',
body: formData
........
I'm posting to an API using axios, and using the data from the response I want to make another API request but I'm running into issues saying that axios is not defined.
The calls, that are in inside my Vue login component, are the following:
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
and as I mentioned earlier, the error in my console is the following: TypeError: Cannot read property 'axios' of undefined.
I´ve tried writing the second request without this. but I'm having the same issues. Where am I going wrong?
You have to use an arrow function here.
Regular functions have their own this value.
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
Or if you prefer old-fashioned way you can save this reference to some variable to have access to it in the callback:
const self = this
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
self.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})