'react js send object to node js
I send the object to the backend(Node js) when API call. but I check objects using console log. I checked using POSTMAN. When I checked POSTMAN, I worked very well. But I try to pass an object in the frontend (react js) it is shown as undefined.
getnotification(){
const userdetails={
userid:"1235",
username:this.state.name
}
axios.get('http://localhost:4000/notification/',userdetails)
.then((res)=>{ this.setState((cur) => ({ ...cur, notification: res.data.reverse() }));
})
}
Solution 1:[1]
If you want to [POST]
, you need to use axios.post(url, body)
.
Following are the possible method signatures for axios.
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Read more https://axios-http.com/docs/api_intro/
Solution 2:[2]
You ar missing the "{}". You can do something like this:
const userDetails = {
userid:'1235',
username:this.state.name
}
axios.get('/user', {
params: userDetails
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Solution 3:[3]
You can use the async / await syntax instead of the callback function, but it's not supported by all browsers. And you can add error handling to the async function in simple ways.
async getNotification() {
const userDetails = {
userid: "1235",
username: this.state.name
}
try {
const res = axios.get('http://localhost:4000/notification/', userDetails)
this.setState((cur) => ({...cur, notification: res.data.reverse()}));
} catch (error) {
console.log(error);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | TOT?M |
Solution 3 | Jakub Kurdziel |