API request working in Postman but not in fetch() method of React Native app - reactjs

I am trying to do a fetch() method in my React Native app:
return fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
...headers
},
body: body
})
Here url is <IP address>:<port>/api/token
method is 'POST'
headers is {Content-Type: "application/x-www-form-urlencoded"}
and body is
grant_type=password&username=<username>&password=<password>&pushtoken=&primaryhost=<primary host IP>&primaryport=<primary host port>&secondaryhost=<secondary host IP>&secondaryport=<secondary host port>&osscustomer=103&deviceid=<device ID>&version=1.0&osversion=9&deviceversion=1.0
When I use these values in a Postman request, it works fine, but when I run the fetch() method in my React Native app, it gives the error e = TypeError: Network request failed at XMLHttpRequest.xhr.onerror.
Does anyone know why this might be?

change 'Accept' to Accept without single quites.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request:How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Use the following format:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Better to use axios for http/https requests:axios package

It's working fine for me. Try this it may help
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);
})

Related

Fetching an API in react

I am new to React, And I am Stuck. I am trying to make a signup page, having textboxes: name,phonumber,email,password.
What I want is, When I click on login button, all these details should be sent over POST to my API, and response is fetched and stored.
API:
http://localhost:5000/api/users/signup
Method:
POST
Request to my api is send in this way:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;#ccc.in",
"password": "1234566788"
}
Can anyone please explain me using code how to send this data to my api on clicking signup, and fetching response
Don't need to use any third party libraries, just use the Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Source: Mozilla MDN
you need to install axios or fetch axios is good axios
axios.post('http://localhost:5000/api/users/signup', {
name: "Devanshh Shrivastvaaaa",
phoneNumber":"982964XXX8",
email: "devannnnnshh;#ccc.in",
password: "1234566788"
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
also check for further

React native fetch() 403 status

I have an API endpoint working good in postman with the bellow options
The above request can get 200 status and got a response. Now I am trying to implement the same API with React Native using fetch method.
fetch('https://example.com/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx'
},
body: {
"useremail": "testuser#example.com",
"userpassword": "123456"
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
The above code was not working and I am getting 403 status.
Have you tried this
The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all requests:
android:usesCleartextTraffic="true"
feel free for doubts
You are passing data without converting it to json will make problem here
fetch('https://example.com/api/user/login', {
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
},
body: JSON.stringify({ // convert object to json
"useremail": "testuser#example.com",
"userpassword": "123456"
}) ,
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that access to the requested (valid) URL by the client is Forbidden for some reason. The server understood the request, but will not fulfill it due to client related issues.
so for first step in your postman use a fake user password to see if you get 403 again ,
if you got, that means you have problem in your sending your react native data.
so you should focus on your sending request code then,
According to docs
you can post like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
be sure that you are sending your user pass correctly and not missing anything like misspellings
hope this helps you.

How to pass authentication token with every React request to back end API?

I have an existing application in which REST APIs are already developed. I am thinking to develop a front end using React JS and front end should call my REST APIs with every request.
However when I login to my application then a token is generated which is passed to every subsequent requests as an authentication header. How can I achieve this using React?
I am a beginner in React.
You can use axios as a library, and add this as a configuration
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
https://www.npmjs.com/package/axios
Use fetch. Example:
var data = {myData: 'hello'}; // or just 'hello'
fetch(YOUR_URL, {
method: 'POST', // or GET
body: JSON.stringify(data), // data can be string or object
headers:{
'Authorization': YOUR_TOKEN,
// ... add other header lines like: 'Content-Type': 'application/json'
}
}).then(res => res.json()) // if response is json, for text use res.text()
.then(response => console.log('Response:', JSON.stringify(response))) // if text, no need for JSON.stringify
.catch(error => console.error('Error:', error));
First receive the token and save it to your browsers local storage using localStorage.setItem('token', JSON.stringify(userToken));
Then, everytime you send a request, you get this token from your local storage using localStorage.getItem("token")
Thereafter, if you were POSTing an object with a key value of ID: 1, you would do:
await fetch("your_API_endpoint", {
method: 'POST',
headers: { 'Content-Type': 'application/json', "Authorization": localStorage.getItem("token") },
body: JSON.stringify({'ID': '1'})
})

Azure App Service Authentication - 302 when trying to GET /.auth/me

I have a reactjs web app which is hosted on Azure App Services, using App Service Authentication.
My app authenticates properly and from inside the app I'm attempting to GET /.auth/me so that I can read the access tokens to use for some future API requests but am receiving a 302 in response. The response redirects to login.microsoft.com even though the first request (to load the app) has already been authenticated.
const headers = {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'credentials': 'include'
};
return (dispatch) => {
const requestOptions = {
method: 'GET',
headers: headers,
};
return fetch("/.auth/me", requestOptions)
.then(parseResponseAndHandleErrors)
.catch(error => {
console.error(error)
});
}
I think I must be missing a cookie or a header in the GET but the docs don't give much information: https://learn.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#retrieve-tokens-in-app-code
From your client code (such as a mobile app or in-browser JavaScript), send an HTTP GET request to /.auth/me. The returned JSON has the provider-specific tokens.
I have tried setting 'credentials': 'same-origin' but that didn't make any difference.
I managed to figure this out after looking in to more detail at the 'credentials' option of the fetch() API.
'credentials' : 'same-origin' should not be included in the headers, but rather as a seperate request option:
const headers = {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
};
return (dispatch) => {
const requestOptions = {
method: 'GET',
headers: headers,
'credentials': 'same-origin' //credentials go here!!!
};
return fetch("/.auth/me", requestOptions)
......
}

headers are not being set into AXIOS post request

I am working on react-redux App. When i am making Api Post request to Rest Api(on CORS). Headers are not being set. But when i try this in postman it work perfectly.
this is the code:
I want to send TOKEN(for testing).
post: (endPoint, data) => {
return axios({
method: 'post',
url: `${apiPath}/${endPoint}`,
data: data,
headers: { "Content-Type": "application/json", 'TOKEN': 1111}
}).then((res) =>{
return res;
})
}

Resources