How to upload multi image in api? - reactjs

const addProdFunc = () => {
const proheader = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
};
axios
.post(
process.env.REACT_APP_ADMIN_API_URL + "product/",
{
image_path: pimg,
product_img: simg[0],
},
{
headers: proheader,
}
)
.then((response) => {
console.log(response);
});
};
I tried a single image it works but when I try to upload multiple images it doesn't upload.
when I put in the console image data comes like this.
same code for both fields in the backend.

You need to make sure that your API expects one or more images. You seem to get the images correctly from the front-end side but the back-end is not expecting that.

Related

Host images on imgbb sometimes showing error

I upload images on one of reactjs project and host on imgbb but sometimes posting is working successfully and sometimes showing error.message: "Can't get target upload source info".
What's the problem actually ?
const [coverPhoto, setCoverPhoto] = useState([]);
const onChangeCover = (data) => {
setCoverPhoto(data)
const imgAPIKey = 'c83daa0cd70c09ca51b747864c4a22e1'
const image = data[0].file
const formData = new FormData()
formData.append('image', image)
const url = `https://api.imgbb.com/1/upload?key=${imgAPIKey}`
fetch(url,
{
method: "POST",
body: formData
})
.then(res => res.json())
.then(async result => {
console.log('imgbbCover', result)
const coverPhoto = result.data.url
await fetch(`http://localhost:5000/profiles/${email}`,
{
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ coverPhoto })
})
})
}
see the console
Finally I've find a reason not posting the images properly sometimes is actually the freemium version has some limitations, one is not hosting every time properly...
Also tried the Cloudinary free hosting and found the same issue .

React image upload not working through fetch

const submitData = (ev) => {
ev.preventDefault();
let formData = new FormData();
formData.append("topicName", topicName);
formData.append("topicMessage", topicMessage);
formData.append("pictures", pictures);
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json, text/plain, */*",
},
body: formData,
};
const sessionId = localStorage.getItem("sessionId");
let url = FormatUrl(`/api/v1/support/topic?sessionId=${sessionId}`);
fetch(url, requestOptions)
.then((res) => res.json())
.then((res) => {
ToastsStore.success(
"Ваше обращение отправлено, среднее ожидание ответа 6 часов"
);
})
.catch((error) => {
console.log(error);
});
};
Here i am sending data to upload file like this but no response getting back from Server.
Same things working in postman. Please refer to the screenshot.
Please take a look how can i fix it.
I've done some researches here.
I found this nice website: https://muffinman.io/blog/uploading-files-using-fetch-multipart-form-data/ .
Apparently you should try to remove the content-type header.
Though if it doesn't work, please inspect the network and share the request made on chrome / firefox. (F12 -> Network and then try your request)
Instead of appending data to the object like formData.append("topicName", topicName), use something like formData["topicName"] = topicName
This might solve your issue. Let me know if that helped.

axios doesn't send post data to the back-end

I'm new to react and.my problem is that i'm going to make a post request to my node back-end. using react-redux and axios. the thing is my back-end doesn't even hit the request. and no action on the network tab in the browser ether
I have tried lots of another answers but doesn't work
this code is in my redux action page
export const postNominationPayments = function
postNominationPayments(candidatePayments) {
let nominationPayments = {
depositor:candidatePayments.depositor,
depositAmount:candidatePayments.depositAmount,
depositeDate:candidatePayments.depositeDate,
filePath:candidatePayments.filePath,
status:candidatePayments.status,
nominationId:candidatePayments.nominationId
};
return function (dispatch) {
console.log("**",nominationPayments);
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
axios
.post(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
.then(response => {
console.log("))))))))))))",response);
// dispatch({
// type: POST_NOMINATION_PAYMENTS,
// payload: response.data
// })
})
.catch(error => {
console.log("===",error);
// dispatch({ type: AUTH_FAILED });
// dispatch({ type: ERROR, payload: error.data.error.message });
});
};
}
post data is coming as expected.also the back works correctly using postman. but it's not working.
couldn't think of a solution.
what is wrong with my code?
thanks in advance
It should be
axios.post(
`${API_BASE_URL}/nominations/payments`, nominationPayments,
{headers: headers}).
One can drop headers section as well a default is application/json
The way you are passing data to axios post request is incorrect. You need to pass something like below
Change
axios(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
To
axios.post(
`${API_BASE_URL}/nominations/payments`,
nominationPayments,
{
headers: headers
}
)
axios.get and axios.post takes different kind of arguments and could be hard to remember.
So I usually just stick to the more verbose way:
axios({
method: 'post',
url: `${API_BASE_URL}/nominations/payments`,
data: {
nominationPayments
},
headers
})
.then(response => {
// ...
})
.catch(error => {
// ...
})
Have you checked whether your MongoDB server is up and running?
In my case, my React server was running, however, my MongoDB servers were not. I ran both simultaneously and was able to post data to the back end.

MIcrosoft API get Calendar Event description and show it appropriately

In my React project, I made an Axios call to populate a Calendar Event List taking data from Microsoft Outlook Calendar (using Microsoft API). The result is the following
As you can see only event description give me a problem. Indeed to show the event description it shows me an HTML string without the event detail.
I read that I have to put in the header of my request Content-type:text, but I tried and It doesn't work. How I can solve that? This is my Axios Request
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
).then(response => this.setEvents(response.data.value))
.catch((error) => {
console.error(error.response);
});
}
For that matter Prefer: outlook.body-content-type="text" header needs to be specified.
According to documentation:
To specify the desired format to be returned in the Body and
UniqueBody properties in a GET request, use the Prefer: outlook.body-content-type header:
Specify Prefer: outlook.body-content-type="text" to get a message body returned in text format.
Specify Prefer: outlook.body-content-type="html", or just skip the header, to return the message body in HTML format.
Example
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
return axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Prefer' : 'outlook.body-content-type="text"'
}
}
);
}
You need to give axios a config object. Currently, you are using the get property, that is why your code doesn't work currently:
axios({
url: `https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-type": "text"
},
})
You can read more here: https://github.com/axios/axios

Mock Postman request into Axios?

I'm trying to construct my axios to be able to mimic the postman request but failed. Please help to have a look
const ax = axios.create({
timeout: 30000,
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});
// Attempt register operation
ax.post('https://url/5bc9ff9628d79b6d274165da/update.json', {
body: JSON.stringify({
json: JSON.stringify({ "stat": "Delivered" })
})
})
.then(({ data }) => {
console.log('DEBUG::success!!! data::', data);
})
.catch((err) => {
console.log('DEBUG::err', err);
});
You can make use of the code-generation feature in Postman.
Click on Code (below Save button) > Search for 'Axios' > NodeJS - Axios
Docs for code generation in Postman: https://learning.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets/
2022 Update
Click on </> icon in right side nav bar
Select Axios from drop down

Resources