how can we get post data from fetch function in react native to express api? - express

Question:
How can we get post data from fetch function in react native to express api?
Issue Faced:
I tried the following process but didn't got those variables in back-end API.
How can the variables be achieved in the backend API? Any suggestions are highly appreciated.
Here is the reactive native fetch function:
REACT NATIVE FETCH FUNCTION:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
The express API is given below:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}

Fetch also takes an optional second argument that allows you to
customize the HTTP request. You may want to specify additional
headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will
return a Promise that makes it straightforward to write code that
works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

Related

paypal authorization unsupported_grant_type Grant Type is NULL in axios post request

I am trying to integrate paypal in my app and i got 400 error [unsupported_grant_type] Grant Type is NULL
axios
.post(
'https://api.sandbox.paypal.com/v1/oauth2/token',
{ grant_type: 'client_credentials' },
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
auth: {
username:
'clientId',
password:
'secret'
}
}
)
.then(response => {
console.log('response', response.data);
})
.catch(err => {
// console.log('error', { ...err });
console.log('error', err);
});
what i am doing wrong?
Note: it works fine in postman
I found the solution..
stringify the body..
add
const qs = require('querystring');
qs.stringify({ grant_type: 'client_credentials' })

Possible Unhandled Promise Rejection / Error: Request failed with status code 400

I know there are some answers on this and I read them all. But none of them helped.
So this is my error message:
And here is my action:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then(response => response.data)
return {
type: "REGISTER_USER",
payload: request,
}
}
Thanks!
Give a try to fetch the library for making API call.
function registerUser(data){
return fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((apiResponse)=>{
console.log("api response", apiResponse)
return {
type: "REGISTER_USER",
api_response: apiResponse.data
}
})
.catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
Invoking the above function
let data = {
email: "youremail#gmail.com,
password:"yourpassword"
}
registerUser(data).then((response)=>{
console.log(response)
})
Log error and succes then check:
export function registerUser(data){
const request = axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
You should use catch handler wherever you call an api with a promise, because you don't when the api will fail and you have to handle the error.
export function registerUser(data){
return axios({
method: 'post',
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers: {
'Content-Type': 'application/json'
}})
.then(function (response) {
//handle success
return {
type: "REGISTER_USER",
payload: response.data,
}
})
.catch(function (err) {
//handle error
return {
type: "REGISTER_USER_FAILED",
payload: null
}
});
}
Call the function like this
const data = {
email: 'asd#asd.asd',
password: 123
}
registerUser(data).then((response)=>{
console.log(response)
})
export function registerUser(data){
return axios({
method: "POST",
url: `${REGISTER}${API_KEY}`,
data: {
email: data.email,
password: data.password,
},
headers:{
"Content-Type":"application/json"
}
}).then((api_response)=>{
return {
type: "REGISTER_USER",
api_response: api_response.data
}
}).catch(function (error) {
return {
type: "REGISTER_USER",
api_response: {success: false}
}
})
}
//Invoking the above function
let data = {
email: "youremail#gmail.com,
password:" password"
}
registerUser(data).then((response)=>{
console.log(response)
})

await is giving Refrence error in react-native

I have the following code
async _onPress() {
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === 'success')
//I am getting error here
await AsyncStorage.setItem('token', responseJson.token);
//moving on to the main screen if server return success
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
.catch((error) => {
console.log(error);
});
} else {
Toast.show({
text: "Please Connect To Internet",
type: "danger"
});
}
});
}
I am trying to save the token i receive from my API server using AsyncStorage.I get the following errors
Expression statement is not assignmentor call
and RefrenceError:await is not defined
when i try to use await in the location.
But when use the same code at the beginning of the function i get no errors.
I dont know what is wrong. Is it not allowed in async await? I am not too familiar with these.
If _onPress calls some async functions and you want to wait for all of them to finish, you must place an 'await' in front of every single one of them. In addition, every async function, including async callback functions, must be declared async too.
The complete code:
async _onPress() {
**await** NetInfo.isConnected.fetch().then(**async** (isConnected) => {
if (isConnected) {
**await** fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then(**async** (responseJson) => {
if (responseJson.status === 'success') {
**await** AsyncStorage.setItem('token', responseJson.token);
Actions.MainScreen();
} else {
Toast.show({
text: "Wrong username or password!",
type: "danger"
});
}
})
}
})
}

FacePlusPlus, "error_message": "MISSING_ARGUMENTS: api_key", with React Native fetch request

I'm fairly new to react native and I'm trying to test out using the FacePlusPlus API (https://console.faceplusplus.com/documents/5679127).
Here, I've tried putting 'api_key' in the body, however, I've also tried putting it in headers too. Neither has worked.
componentDidMount() {
var url = 'https://api-us.faceplusplus.com/facepp/v3/detect';
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_key: 'blahblahblah',
api_secret: 'blahblahblah',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
In render(), I put console.log(this.state.data) where data is an array to see the response, however all I keep getting is
Object {
"error_message": "MISSING_ARGUMENTS: api_key",
}
To solve this problem you have to set Content-Type header to 'application/x-www-form-urlencoded'
and pass your arguments as formData.
I put the example with using 'request' npm package.
const request = require('request');
request.post({url:'https://api-us.faceplusplus.com/facepp/v3/compare', formData: {
api_key: 'your api key',
api_secret: 'your api secret',
image_url1: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/George_Lucas_cropped_2009.jpg/220px-George_Lucas_cropped_2009.jpg',
image_url2: 'https://imgix.bustle.com/uploads/getty/2018/6/13/e4c5921d-3e23-4f13-87fe-0180005d0ace-getty-929360234.jpg?w=970&h=582&fit=crop&crop=faces&auto=format&q=70'
}}, (err, httpResponse, body) => {
if (err) {
return console.error('error', err);
}
console.log('success ', JSON.parse(body));
});

AsyncStorage not storing an item in react native after http success response

I have just tried to store an item in AsyncStorage after success
response.I have made http request using axios.I have little bit confused i tried already how to store data using AsyncStorage but when i trying to store an item on http request onSucess() is not storing.please help me where i made mistakes.
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(function (response){
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=JSON.stringify(response.data.token);
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
Alert.alert("success:", accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(function (error) {
Alert.alert("Error:",error);
});
Use below fetch method
fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: this.state.email, password: this.state.password})
}).then((response) => response.json())
.then((responseData) => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
}).catch((error) => {
Toast.show("There is a Problem on your network connection");
});
Here is the example use that :
`fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: <email> ,password: <password>})
}).then((response) => response.json())
.then((responseData) => {
if(responseData.STATUS == true){
AsyncStorage.multiSet([
["state", JSON.stringify(responseData.DATA[0])],
["country", JSON.stringify(responseData.DATA[1])]
]);
}
});`
Try this
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(response => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(error => {
Alert.alert("Error:",error);
});