'react-native-image-picker' for uploading image in my application, Sometimes it is uploading and sometimes i am getting [TypeError: Network request failed] below is the code:
FormData in my component:
//image is :file:///data/user/0/com.testApp/cache/rn_image_picker_lib_temp_0d38d959-6ece-4750-a215-4b3f68002f4e.jpg
let formData = new FormData();
formData.append('images', { uri:image, name: imageSelected?.fileName, type: 'image/png' });
const response = await updateUserProfile(userDetails,formData)
Service call:
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: data,
});
return await response;
};
In Postman i have checked the api is working fine, What would be the problem in my code.
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: JSON.stringify(data),
});
return await response;
};
Related
I am trying to convert the below code which is using request module to axios module to send the POST request.
request module code:
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
var options = {
'method': 'POST',
'url': url,
'headers': {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Accept': 'application/json'
},
formData: {
'image': {
'value': imageFile,
'options': {
'filename': imgName,
'contentType': null
}
}
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log("SUCCESS");
});
The above code works fine and the image is posted successfully with the request module. But when I convert the same to axios, I am getting a 500 Error. (AxiosError: Request failed with status code 500)
axios module code:
const FormData = require('form-data')
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
const bodyFormData = new FormData();
bodyFormData.append("image['value']", imageFile);
bodyFormData.append("image['options']['filename']", imgName)
// bodyFormData.append("image['options']['contentType']", null)
console.log(bodyFormData)
const formHeaders = bodyFormData.getHeaders();
axios.post(url, bodyFormData, {
headers: {
...formHeaders,
'Cache-Control': 'no-cache',
'Accept': 'application/json',
}
}).then(function (response) {
console.log('SUCCESS');
}).catch(function (error) {
throw new Error(error);
});
Can anyone find out what I am doing wrong here?
Is there any other way to post the image using axios other than using form-data?
See the documentation for FormData#append(). You can provide extra data like the file name as the 3rd options parameter
const bodyFormData = new FormData();
// Pass filename as a string
bodyFormData.append("image", imageFile, imgName);
// or to specify more meta-data, pass an object
bodyFormData.append("image", imageFile, {
filename: imgName,
contentType: "image/jpeg",
});
axios.post(url, bodyFormData, {
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
...bodyFormData.getHeaders(),
},
});
Under the hood, request() does something very similar with the exact same form-data library. See request.js
I am trying to replace a fetch with axios. I keep getting undefined in my console log.
async componentDidMount() {
console.log('app mounted');
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await axios({
method: 'get',
url: Config.apiUrl + `/api/Orders/GetAllInvoices`,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token }
});
console.log(`axios: ${response.json}`)
this.setState({ invoiceList: response.json });
//const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
// method: "GET",
// headers: headers
//});
//const json = await response.json();
//console.log(json);
//this.setState({ invoiceList: json });
...
... the commented out fetch is working. I just now added the .json even though axios should not need it. Neither way works. What am I doing wrong?
Did you even console.log(response) just to see whats inside of it?
I guess you dont, because response is an object witch has no json key in it. You should use response.data
So I am trying to send data from canvas's api using a GET and use that information and send a POST from the same endpoint to discord using node fetch. I can receive data from canvas without issue and I console log to make sure I have to right data, but I can't seem to get any information to discord. I am using discords webhooks and I can't figure out where I am going wrong.
fetch(url + `courses/${course}/discussion_topics` , {
method: "GET",
headers : {
'Authorization' : 'Bearer <auth token>',
'Content-Type' : 'application/json'
}
})
.then(res => res.json())
.then(data => {
console.log(data[0].id);
console.log(data[0].title);
console.log(data[0].message);
}
)
.then(fetch("https://discord.com/api/webhooks/893327519103746149/<webhooktoken>", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {content: 'hello world'}
}))
.catch(err => console.log(err))
});```
As mentioned in the comment, just in case you have some typo or misunderstanding.
Also, you need to JSON.stringyify your body.
Please try the example below:
fetch(url + `courses/${course}/discussion_topics`, {
method: "GET",
headers: {
Authorization: "Bearer <auth token>",
"Content-Type": "application/json",
},
})
.then(res => res.json())
.then(data => {
console.log(data[0].id);
console.log(data[0].title);
console.log(data[0].message);
})
.then(() =>
fetch(
"https://discord.com/api/webhooks/893327519103746149/<webhooktoken>",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
username: "Canvas-Bot",
content: "hello world",
}),
}
)
.then(res => res.json())
.then(data => {
console.log({ data });
})
)
.catch(err => console.log(err));
Another approach would be in async/await. I think it is cleaner.
(async function main() {
try {
const res1 = await fetch(url + `courses/${course}/discussion_topics`, {
method: "GET",
headers: {
Authorization: "Bearer <auth token>",
"Content-Type": "application/json",
},
});
const data1 = await res1.json();
console.log(data1);
const res2 = await fetch(
"https://discord.com/api/webhooks/893327519103746149/<webhooktoken>",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
username: "Canvas-Bot",
content: "hello world",
}),
}
);
const data2 = await res2.json();
console.log(data2);
} catch (err) {
console.log(err);
}
})();
I am trying to upload a file(uploadType=multipart) to Drive API V3 using fetch but the body is wrong as it is creating a file with the title unnamed.
var tmpFile=document.getElementById('inputFile').files;
tmpFile=tmpFile[0];
await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST', // or 'PUT'
headers: {
'Authorization': 'Bearer '+accessToken,
},
body: {
metadata:{
'name':tmpFile.name,
'Content-Type':'application/json; charset=UTF-8'
},
media:{
'Content-Type': '*/*',
'name':tmpFile
}
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Your metadata is not being properly uploaded if its uploading with a name of unnamed
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const filePath = "./sample.txt";
const accessToken = "###";
token = req.body.token;
var formData = new FormData();
var fileMetadata = {
name: "sample.txt",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
contentType: "application/json",
});
formData.append("data", fs.createReadStream(filePath), {
filename: "sample.txt",
contentType: "text/plain",
});
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
method: "POST",
body: formData,
headers: { Authorization: "Bearer " + accessToken },
})
.then((res) => res.json())
.then(console.log);
Uploading Files of multipart/form-data to Google Drive using Drive API with Node.js
I am trying to pass both formData and an apiKey in the body of a POST request, but it seems like its not working in my code below. What is the right syntax of doing that?
static login = (formData) => {
return fetch('/api/login', {
method: 'POST',
body: { formData,
JSON.stringify({
apiKey: 'xxxxxxxx'
}) },
headers: {
'Content-Type': 'application/json'
},
credentials: 'same-origin'
}).then(r => r.json())
}
I'm pretty sure that's just request-promise, but here
var login = (formData) => {
return fetch('/api/login', {
method: 'POST',
body: { formData:formData,
json:JSON.stringify({
apiKey: 'xxxxxxxx'
})
},
headers: {
'Content-Type': 'application/json'
},
credentials: 'same-origin'
}).then(r => r.json())
}
The body object needs to have keys assigned to the values
On the server, you can access them as body.formData and body.json