Using data received from Axios Post request response - reactjs

Can someone pls give me some advice?
I need to create a report of all messages I sent via rest API.
I got my rest api post request working. What i need now is to extract some data from the Response and use it outside the Axios request. Ideally in another component. Context API doesn't work.
Data can be grouped into object i called stats.
Thats my axios request:
axios.post(url, glbody, {headers:headers})
.then((response) => {
const stats ={
id: response.data.messages[0].dateTime,
date: response.data.messages[0].dateTime,
from: response.data.messages[0].origin,
to: response.data.messages[0].destination,
status: response.data.messages[0].status,
}
})
.catch((error) => {
console.log(error);
})
}
Thanks!

Related

how to use data from response section of post request in react js of django api call?

this data i want to access
this is my api call
api
.post("/auth/registration/", data)
.then((res) => {
console.log(res);
localStorage.removeItem("access");
localStorage.removeItem("refresh");
alert("Registration Successfull");
})
.catch((error) => {
console.log(Response.password1);
alert(error.message);
console.log(msg);
localStorage.removeItem("access");
localStorage.removeItem("refresh");
});
i want to alert the message came from backend in responce section ,how do i do this
Wrap the code in useEffect hook.

Why am I getting empty array in fetch request to MongoDB from ReactJS?

I am trying to fetch all the articles from a document in MongoDB in React. It is perfectly working in Backend with NodeJS when I tested with Postman. But in Frontend , React, I am getting empty array. How to solve this.
Server.js (Backend)
app.get('/api/articles', async (req, res)=>{
const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser:true, useUnifiedTopology:true})
const db = client.db('my-blog')
const articleInfo= await db.collection('articles').find({}).toArray(function(err, result){
if (err) console.log(err)
res.status(200).send(result)
client.close()
})
})
articlePage.js (FrontEnd)
componentDidMount(){
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
const fetchdata = fetch('/api/articles/').then(res=>res.json())
.then(data=>this.setState({articles:data}))
console.log(this.state.articles)
}
Api address is set up in package.json with proxy:http://localhost:8000
How to get the documents data from MongoDB in React?
Firstly, check if you the API call went through to the server from your React app. If it has, then check for the response code in the network. In your case, 200 is where you get the desired result from the API. If you are not getting the desired result, then check your collection and document names and also arguments your are passing in the query.
As setState is not synchronized, you have to access it in the callback.
this.setState({ articles: data }, () => {
console.log(this.state.articles)
})

what am i missing ? using axios to perform a delete request , troubleshooting with req.params.id using mongodb as bakcend

I am trying to execute a function which deletes a post from the local mongodb database .
I Have tested the code with postman it is working but in the frontend i am using axios and the id is needed to be passed as a request parameter ,
but i am getting an error. My code is unable to pass the id parameter , but backend code looks ok.
xhr.js:166 DELETE http://localhost:3000/api/posts/?id=5da802aa8b54d7220f84110e 404 (Not Found)
axios.delete('/api/posts/',{params:{id:'xyz'}})
although i tested in postman by directy inserting the id
(http://localhost:5000/api/posts/xyz_id) with delete request, and it worked.
/////backend
delete(req, res, next){
const postId = req.params.id;
Post.findOneAndDelete({ _id:postId })
.then(post => res.status(204).send(post))
.catch(next);
}
//////frontend
const deletePost =()=>{
axios
.delete('/api/posts/', { params:{ id:'5da802aa8b54d7220f84110e'}})
.then(res => console.log('deleted'))
.catch('err', err => console.log(err));
};
The second argument of the axios request is typically used to pass in a req.body. In your backend logic, you're trying to use data available in the req.params, which should be passed via the route path on the front-end. Try this instead:
const deletePost = () => {
axios
.delete(`/api/posts/${5da802aa8b54d7220f84110e}`) //you can swap the number with an actual variable
.then(res => console.log('deleted'))
.catch('err', err => console.log(err));
};
This assumes your API route looks something like app.delete("/api/posts/:id")
Validate that you don't have to provide some Authorization in headers:
const deletePost =()=>{
axios
.delete('/api/posts/:id', { params:{ id:'5da802aa8b54d7220f84110e'}})
.then(res => console.log('deleted'))
.catch('err', err => console.log(err));
};

Api fetch responses Blob structure in React Native app

I'm consuming a web api from my React Native Android project. After updating my react-native version to 0.60.3 my response data is not returning JSON, it returns Blob data structure.
This is what I get from then(res=>{...})
Please look at the image
Screen-Shot-2019-07-18-at-17-25-10.png
The _bodyInit object was returning JSON. But now it returns Blob that I can not reach from Js code.
I tried using functions res.json(), res.text()
They worked! But this time I just got data inside the _bodyInit. I can not reach other parameters like ok, header etc.
This is what I've tried. Like I said, it works. But it returns response with just my data, not other parameters like ok, headers etc.
.then((res) => res.json())
.then((res) => {
if (res.ok) {
// No 'ok' element anymore after .json()
}
});
In the 'devtools' if I click the '_bodyInit' object. Simulator gives error below.
Screen-Shot-2019-07-18-at-17-32-49.png
Do you have any idea to solve this issue?
Thanks in advance!
ok property is with response before you call json method on it. If your response contains json, call json to serialize body as json, if response contains blob, call .blob to serialize body as blob. See more proerties of Response here.
.then((res) => {
console.log("response.ok", res.ok)
// print headers,
console.log("headers", res.headers.forEach(item=>console.log(item)))
// if response if json, call res.json
return res.json()
})
.then((res) => {
// here you will only get json data, not other properties.
console.log("json data is ", res)
});
SOLVED
I found two way to solve this problem.
Using .then() after using .json()
.then((res) => {
if (res.ok) {
res.json().then(res=>{
console.log(res)
})
} else console.log("not ok")
});
Using async and await
.then(async res => {
if(res.ok) {
const response = await res.json()
console.log(response)
} else console.log("not ok")
})
That would be great to see other solutions from you. Thanks.

How to fetch data from Microsoft Custom Vision API using ReactJS

I need some help regarding the use of Custom Vision. I built an image classifier in order to detect car damages.
So what I am trying to do: when I try to input an image and click the submit button, I want to be able to call the Custom Vision API and get the results in order to be able to analyze them later using ReactJS
I tried using AXIOS and the componentDidMount() method, but I can't seem to get a hold of them.
componentDidMount(){
axios.get('url: "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/...",
// Request headers {
prediction: ("Prediction-Key","xxx");
content: ("Content-Type","xxx");
},
type: "POST",
// Request body
data: imgContent,
processData: false')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
your request type is post and you are using axios.get()
Check your code, // Request headers {
prediction: ("Prediction-Key","xxx");
content: ("Content-Type","xxx");
},
The first bracket seems to be commented out so this may be a potential problem.
You should use async/await with the componentDidMount method.
An example
async componentDidMount() {
const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
}

Resources