I am using axios to fetch api and i am not able to fetch api in multiple table row only one row display the data and when i refesh the page another value came out but not able to access the api in next row
Code for Axios
function getPostData(Player, IP, Port, channelName) {
//console.log("insideFunction Row1"+Player);
var data = {
PlayerName: Player,
ChannelName: channelName,
Port: Port,
IpAddress: IP
}
axios({
method: 'post',
url: 'http://localhost:9763/api/getPlayerStatus',
data,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
auth: {
username: 'admin',
password: 'password'
}
}).then(response => {
console.log([response.data]);
Postdata([(response.data)]);
// Postdata(prevArray => [...prevArray, response.data]);
}).catch(error => {
console.log("Error In Post Data", error);
});
}
Related
I've tried
axios.get(url, {headers:{},data:{}})
But it doesn't work with this.
You should refer to https://github.com/axios/axios#request-config
Check the section for data and header.
As far as I know you can't send body data with GET request. With get you can have only Headers. Just simply change to POST and then you can do something like this :
const bodyParameters = {
key: "value",
};
const config = {
headers: { Authorization: `Bearer ${userToken}` },
};
axios.post("http://localhost:5000/user", bodyParameters, config)
.then((res)=> {
console.log(res)
})
.catch((err) => console.log(err));
};
or if you want to send headers with GET request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
https://stackoverflow.com/a/54008789
yeah, it's true it doesn't work to send body in Axios get even if it works in the postman or the backend.
You can try this:
const getData = async () => {
try {
const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
method: 'POST',
body: JSON.stringify({
id: id,
title: 'title is here',
body: 'body is here',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
}
You can send data in a get request by using the config object and the params option of the config object. This is a workaround and it works, but on the server the data sent is available as request.query not as request.body. Based on the example below you would access your params data on your server using request.query.user_id. It should be noted that using this method will also append the params to your request url which could have unintended consequences based on your specific situation. For example, the url for the request below would be sent as example.com?user_id=1234. You can read more about the axios request config here.
axios.get(
'example.com/',
{
params: { user_id: 1234 },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
);
In my project the API requires some data to be passed that is :
Bearer Token
Body - {email: [email_address]} e.g. {email: “mayank#gmail.com”}
Params - Your name i.e https://1234.amazonaws.com/alphabet/mayank
I am doing this in reactjs.
But I am confused how to use params.
My try:
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
};
fetch('https://1234.amazonaws.com/alphabet/mayank')
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},
But this is not working.
You should provide your parameters to the fetch request in an object like this. Read more about how to make post requests here.
fetch('https://1234.amazonaws.com/alphabet/mayank',
{
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
})
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},
I am creating CRUD for my react js application, basically what happen is when I added or post a data it will be added but the table will not update or show the latest data that is added unless you refresh the page.
Here is my code for displaying the data
componentDidMount() {
axios.get('http://mylink')
.then(response => {
this.setState({students: response.data})
})
.catch(error => {
console.log('No data to be shown')
})
}
And for adding data
handleAddData = () => {
axios({
url: 'http://mylink',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: {
students: students
}
})
What i want to happen is when the data is added the table will automatically update without refreshing.
Posts are usually made with one new element, and you update the state's students when confirmed:
axios({
url: 'http://mylink',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: newStudent // must receive this
})
.then( response => {
const { students } = this.state;
this.setState({students: [newStudent, ...students});
})
Be aware that if you expect to received the updated version of the new student from the back-end you should add the very response to the list:
.then( response => {
const { students } = this.state;
const confirmation = response.data;
this.setState({students: [confirmation, ...students});
})
I'm doing a multiple checkbox filter, and I have to send to the server an object with a post method. How can I use fetch to do that? Can I send data using fetch? And from the server I have to receive a filtered list.
Thank you!
Yes you can specify the fetch method with 'POST'
example code here from https://facebook.github.io/react-native/docs/network.html
function getMoviesFromApiAsync() {
return fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson.success;
})
.catch((error) => {
console.error(error);
});
}
I try update the current user email but the Auth0 API response returns 403 error with this payload:
{
"statusCode":403,
"error":"Forbidden",
"message":"You cannot update the following fields: email",
"errorCode":"insufficient_scope"
}
But I pass the scope when I instantiate the lock.
this.lock = new Auth0Lock(clientId, domain, {
auth: {
redirectUrl: 'http://localhost:3000/login',
responseType: 'token',
params: {
scope: 'openid email user_metadata app_metadata picture update:users'
}
},
My script to send the PATCH:
updateProfile(userId, data){
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.getToken() //setting authorization header
}
// making the PATCH http request to auth0 api
return fetch(`https://${this.domain}/api/v2/users/${userId}`, {
method: 'PATCH',
headers: headers,
body: JSON.stringify(data)
})
.then(response => response.json())
.then(newProfile => {
this.setProfile(newProfile)
}) //updating current profile
}
Any ideas?