How do i get the status of my response when using fetch in react-native? - react-native

I am making Log In page for my react native application. My api sends different response when my username and password are valid and invalid. So I want to track and save the status of my response in some state variable and then later perform function accordingly. Please suggest me way to do that.
doSignUp() {
console.log("inside post api");
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: this.state.password,
email:this.state.email,
name: this.state.firstname,
last_name :this.state.last_name,
mobile:this.state.mobile,
ssn:"2222222"
})
}).then((response) => {console.log('response:',response.status);
response.json()}
.then((responseData) => {
console.log("inside responsejson");
console.log('response object:',responseData)
console.log('refresh token:',responseData[0].token.refresh_token)
console.log('access token:',responseData[0].token.access_token);
}).done();
}

As far as I understand you want to know the http status code of your fetch request.
Usually your response object includes a "status" property. So you should be able to receive the status code by using this:
response.status
In case of a successful request this will return 200.

Related

my react-native app fail to send body in POST request to backend url

As i am trying to send my data in form of body in backed url as in backed i have made something if it dont receive body it will send sucess: false, msg: haven't received body else sucess: true, msg: jwt token as if i make request from post man with same data it's working but sending via. native app it fails to send.. any help will be helpfull
As 1st request is from postman and 2nd from my app
const handleLogin = (Enrno, Pass) => {
setError(null);
setIsLoaded(false);
setItems([]);
fetch(config.url + "/login", {
method: "POST",
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
"enrno": Enrno,
"password" : Pass
})
})
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
alert(items[0].msg);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
};
I think you need to put these to headers, not header.
Accept : 'application/json',
'Content-Type' : 'application/json'
So, it should look like this.
fetch(config.url + "/login", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
enrno: Enrno,
password : Pass
})
})

Error trying to fetch access token from Spotify API using Axios

I'm working on a project with Vue using the Spotify API and get stuck trying to get the access token. I'm using axios to make the request but every time I get a 400 status from the server.
This is the way I'm doing it, I have the request inside an action in my Vuex store and I'm not sure if I'm missing something.
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
params: {
grant_type: 'authorization_code',
code: payload.code,
redirect_uri: process.env.VUE_APP_REDIRECT_URI
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.VUE_APP_CLIENT_ID + ':' + process.env.VUE_APP_CLIENT_SECRET).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
json: true
})
.then((response) => {
//handle success
resolve(response);
})
.catch((error) => {
//handle error
reject(error);
})
I would try using data instead of params.
I think data is for the POST body and params is for query string parameters.
Axios Cheat Sheet
You should inspect the request to see what you're sending and then compare that to what you should be sending.

How to check if body in fetch POST has sent to API in react native?

I am building a react native app and got this following error. I want to send inputted message, email, and name to API, but it's not showing any result in API.
Here is the code:
fetch('localserverusingIPaddress', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
}),
})
.then((response)=> {console.warn(response.json())})
//{
// if (response.status){
// return response.json();
// }
// console.warn(response.json())
// return response.json();
//})
//console.warn(response);
//response.json()
//console.warn(JSON.parse(response))})
.then((responseData)=>{
this.showAlert();
console.warn(responseData);
return responseData;
})
.catch((error) => {
console.warn(error);
});
However, when I try to check the inputted texts in iOS
simulator, it's showing the value. It's also showing the values when I post data to API directly with postman. So I start to think that the body was failed to pass to API.
Can anyone please tell me why is this happening and how to fix this? Thank you so much, I'm facing this problem for several weeks...
First step is to make sure if your iOS simulator is actually able to make requests to your localhost or not. If it can't reach your local network, it must throw some kind of connectivity error. However, from your comment above, it seems that is not an issue.
Try this code:
let url = 'localserverusingIPaddress';
let requestObject = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
try {
let response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestObject)
});
responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error(error);
}
Try this and see what is the logged output.
Easiest way to see if the request has actually reached your API is from the API end itself. Your server must have some sort of event logging implemented. See what happens there when you make a request from Postman and compare its output with what happens when you make a request from the app.

How to send data to server and fetched response using react native application?

I am trying to learn react native application by making a simple login page using api call. Where I will send user name and password to api and it will give me response. But I can't do it. Well I am sharing my code here.....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the way of passing my user name and password to server is wrong. Please give me some idea then I can understand what is wrong here.
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I hope this helps.
You need to Stringify the json data to send request as Post method with Json parameters as you are trying to do...
Here is the example code for how to encode data before requesting for response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Here is the sample code for login :
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
As the commentators before me stated, you simply need to stringify your JSON Body. In general, I' suggest that you incorporate e.g. api sauce into you stack. It is a comprehensive wrapper around the axios library, providing standardized errors and an ok key for quick checks.

fetch: Getting cookies from fetch response

I'm trying to implement client login using fetch on react.
I'm using passport for authentication. The reason I'm using fetch and not regular form.submit(), is because I want to be able to recieve error messages from my express server, like: "username or password is wrong".
I know that passport can send back messages using flash messages, but flash requires sessions and I would like to avoid them.
This is my code:
fetch('/login/local', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
}).then(res => {
console.log(res.headers.get('set-cookie')); // undefined
console.log(document.cookie); // nope
return res.json();
}).then(json => {
if (json.success) {
this.setState({ error: '' });
this.context.router.push(json.redirect);
}
else {
this.setState({ error: json.error });
}
});
The server sends the cookies just fine, as you can see on chrome's dev tools:
But chrome doesn't set the cookies, in Application -> Cookies -> localhost:8080: "The site has no cookies".
Any idea how to make it work?
The problem turned out to be with the fetch option credentials: same-origin/include not being set.
As the fetch documentation mentions this option to be required for sending cookies on the request, it failed to mention this when reading a cookie.
So I just changed my code to be like this:
fetch('/login/local', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'same-origin',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
}).then(res => {
return res.json();
}).then(json => {
if (json.success) {
this.setState({ error: '' });
this.context.router.push(json.redirect);
}
else {
this.setState({ error: json.error });
}
});
From Differences from jQuery section of the Fetch API on Mozilla:
fetch() won't receive cross-site cookies. You can’t establish a cross
site session using fetch(). Set-Cookie headers from other sites are
silently ignored.
fetch() won’t send cookies, unless you set the
credentials init option. Since Aug 25, 2017: The spec changed the
default credentials policy to same-origin. Firefox changed since
61.0b13.)
I spent a long time but nothing worked for me.
after trying several solutions online this one worked for me.
Hopefully it will work for you too.
{
method: "POST",
headers: {
"content-type": "API-Key",
},
credentials: "include",
}
I had to include credentials: 'include' in the fetch options:
fetch('...', {
...
credentials: 'include', // Need to add this header.
});