reactjs:unable to send the data in json format - reactjs

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
})

Related

AXIOS get request failed 400 React Native

I am trying to make an axios get request to this endpoint, but I am keep getting this error " [Error: Request failed with status code 400]".
clikk = () => {
console.log('saasdasdl');
var user = 'reflect-user';
var pass = 'user1Pass';
let dta = JSON.stringify({
username: 'test.admin',
password: 'password',
emailAddress: 'test#gmai.com',
});
const headers = {
'Content-Type': 'application/json',
Authorization: 'Basic ctesmtVmbGVjdC11c2VyOnVzZXIxUGFzcw==',
'Access-Control-Allow-Origin': '*',
accept: 'application/json',
};
// var bytes = utf8.encode(user + ':' + pass);
// var authorizationBasic = base64.encode(bytes);
axios({
method: 'get',
url: 'http://IpOfServer:8080/api/v1/user/getUser?all=true',
headers: headers,
data: qs.parse({
username: 'test.admin',
password: 'password',
emailAddress: 'test#gmai.com',
}),
})
.then((res) => {
//const nameList = res.data;
//this.setState({nameList});
console.log(res);
})
.catch((error) => console.log(error));
};
However same request is working in POSTMAN so API may not be involved ish? I've also tried to AXIOS example provided by POSTMAN but I am getting the same error.
var data = JSON.stringify({"username":"test.admin","password":"password","emailAddress":"test6#gmai.com"});
var config = {
method: 'get',
url: 'http://IpOfServer:8080/api/v1/user/getUser?all=true',
headers: {
'Authorization': 'Basic cmVmbGVjdC11c2VyOnVzZXIxUGFzcw==',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Thank you.

Api request with some data in reactjs

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,
});
},

JSON Data is going in request parameter(Instead of String) in React Js

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"
}
});

Api call works on postman but Doenst work on my code

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&parameter2=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);
})

How to send data with fetch in react-redux

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);
});
}

Resources