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,
});
},
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',
},
},
);
I am using fetch mehtod to send and api call but request parameter is going in JSON format insted of String. this is my code plz correct me where i did mistake
export function RestApi(data) {
let BaseUrl = "http://localhost:8000/api/login";
return new Promise((resolve, reject) => {
fetch(BaseUrl, {
method: "POST",
body: JSON.stringify(data)
})
.then(response => response.json())
.then(responseJson => {
resolve(responseJson);
})
.catch(error => {
reject(error);
});
});
}
this.state = {
username: "",
password: ""
};
RestApi(this.state).then(result => {});
your question is a little bit unclear, if you want to send as plain text you can set headers content-type as below.
fetch(BaseUrl, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "text/plain"
}
});
EDIT
actually, sending JSON string should always use application/json
fetch(BaseUrl, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
});
So I have to update some user info ,it works fine on postman but when I try to type it in react-native I must be doing something wrong in the body of the fetch method. In postman I set x-www-form-urlencoded and type the keys like this :
Key ----- Value
moto ----- test
and that seems to work,but when I try to do the same on my code I somehow fail at it,here is my code
updateUser(){
return fetch(url,{
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type":"application/x-www-form-urlencoded"
},
body: JSON.stringify({
moto: this.state.moto
}
})
}
)
I get 200 response which means the call works but I must be seting the parameter moto wrong somehow.
Any ideas ?
"Content-Type":"application/x-www-form-urlencoded"
should be
"Content-Type":"application/json"
form-urlencoded is way different from your body: JSON.stringify().
You'll want to use a FormData object instead:
const body = new FormData();
body.append('moto', this.state.moto);
fetch(url, {
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type": "application/x-www-form-urlencoded"
},
body,
})
APICall = () => {
fetch(‘Your http URL’, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
‘X-Auth-Token’: bearerToken,
},
body: JSON.stringify({
moto: this.state.moto
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.statuscode == 1) {
Alert.alert('Success');
} else {
Alert.alert(responseJson.message);
}
}).catch((error) => {
console.error(error);
});
}
finally fixed it by seting body to
body:
`moto=${this.state.moto}`
it appears that urlencoded headers require parameters in the form of
parameter1=value1¶meter2=value2
componentDidMount() {
return fetch(“Your URL”, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": “token”
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
})
.then((response) => response.json())
.then(function (data) {
alert(“Success”)
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
alert("error occur")
console.log('Request failed', error);
});
}
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})
I cant send my data in json format.
In the server which i was using will accept only json body.
fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
FirstName: this.state.name,
LastName: this.state.last,
EmailAddress: this.state.emails,
Phone: mobis
})
}).then((response) => {
alert(response);
console.log(response)
}).catch((error) => {
console.log(error);
alert(error)
});
am using the above code to pass the data as json
but its not going
the response which am getting is
[object Response]
by using console.log, i got a error is
Response {
type: "cors",
url: "https://api-in21.leadsquared.com/v2/LeadManagement.svc/Lead.Create?accessKey=u$raabd4c6e4e7953f215a7235495367a49&secretKey=a351cd31591c76f19642202ce97cd9417f1c46aa",
redirected: false,
status: 500,
ok: false,
statusText: "Internal Server Error",
headers: Headers,
bodyUsed: false
}
pls suggest me some code guys
You can also try this code
return fetch(HOSTNAME, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ variables: { input: data}})
})
.then((res) => {
return res.json()
})
.then((payload) => {
return payload
}).catch((error) => {
throw error
})
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);
});
}