The body parameters are not working in fetch post react native - api

I have a post request from react native app to chragebee for creating new customer, in postman it works fine, and in the app it works fine also, but the problem is in passing the body parameters from the app to chargebee, so i can not see for example the body parameters in the response body return from chargebee like the email, firstname, lastname , .... after creating user from the app, whereas in postman i can see them.
The postman post request
The response in postman
The response in postman if i remove the body parameters
The function responsible for signup process in react native :
export const ChargebeeCreateUser = (first_name,last_name,email) => {
const bodyParams = {
first_name: first_name,
last_name:last_name,
email:email,
};
return fetch(`https://editpress-test.chargebee.com/api/v2/customers`, {
method: 'POST',
headers: new Headers({
'Authorization': 'Basic ' + encode('site_api_key'),
'Content-Type': 'application/json'
}),
body: JSON.stringify(bodyParams)
})
.then((response) => response.json())
.then(responseJson => {
return responseJson
})
}
Calling the function:
register = async () => {
const { given_name,family_name,email, password } = this.state
let ChargebeeCreateUserResponse = await
ChargebeeCreateUser(given_name,family_name,email);
console.log(ChargebeeCreateUserResponse);
---
---
---
The result of console.log(ChargebeeCreateUserResponse):

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

Spotify returning 200 on token endpoint, but response data is encoded

I'm working through this tutorial on creating an app that uses the Spotify API. Everything was going great until I got to the callback portion of authenticating using the authentication code flow.
(I do have my callback URL registered in my Spotify app.)
As far as I can tell, my code matches the callback route that this tutorial and others use. Significantly, the http library is axios. Here's the callback method:
app.get("/callback", (req, res) => {
const code = req.query.code || null;
const usp = new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
});
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
data: usp,
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
},
})
.then(response => {
console.log(response.status); // logs 200
console.log(response.data); // logs encoded strings
if (response.status === 200) {
res.send(JSON.stringify(response.data))
} else {
res.send(response);
}
})
.catch((error) => {
res.send(error);
});
Though the response code is 200, here's a sample of what is getting returned in response.data: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003E�˒�0\u0000Ee�uS\u0015��\u000e�(\b\u0012h\u0005tC%\u0010\u0014T\u001e�����0��^޳:���p\u0014Ѻ\u000e��Is�7�:��\u0015l��ᑰ�g�����\u0"
It looks like it's encoded, but I don't know how (I tried base-64 unencoding) or why it isn't just coming back as regular JSON. This isn't just preventing me logging it to the console - I also can't access the fields I expect there to be in the response body, like access_token. Is there some argument I can pass to axios to say 'this should be json?'
Interestingly, if I use the npm 'request' package instead of axios, and pass the 'json: true' argument to it, I'm getting a valid token that I can print out and view as a regular old string. Below is code that works. But I'd really like to understand why my axios method doesn't.
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
res.clearCookie(stateKey);
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
},
headers: {
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token;
const refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { Authorization: 'Bearer ' + access_token },
json: true,
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' + querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}));
} else {
res.redirect(`/#${querystring.stringify({ error: 'invalid_token' })}`);
}
});
});
You need to add Accept-Encoding with application/json in axios.post header.
The default of it is gzip
headers: {
"content-type": "application/x-www-form-urlencoded",
'Accept-Encoding': 'application/json'
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
}

Why Axios is not providing response header when app is opening second time?

Here is my API request
const getData= async () => {
const cookie='workid_token=eyJra4rgrtF7SnlSETjIGrFYQy-P2SFmlE6A.Tw_rx0Ut_Kj9zLWRQ9X23w';
const qs = require('qs')
let body = qs.stringify({
gid: '1196'
})
await axios.post(
'https://www.google.com', body,
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
).then(response => {
console.log('data', response);
if (response.data.status === '1') {
const PHPSESSID = response.headers['set-cookie'];
var separatedvalue = PHPSESSID[0];
var sessid = separatedvalue.split('; path=/')[0];
}
}).catch(error => {
console.log(error);
});
};
I am implementing Axios API post request in my React Native application. When I run the application first time I am getting set-cookie value in response headers. If I kill the application and I open it second time I am not getting value in set-cookie. Also not receiving response from the API.
Note: I want to receive value from set-cookie all the times.

Handling API calls with async/await in React Native

I want to have a separate file for API calls -
APIHandler.js
const loginAPI = 'https://..../login';
export async function login(emailAddress, pass) {
const reqOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: emailAddress,
password: pass,
})
};
let response = await fetch(loginAPI, reqOptions);
return response;
}
Now in my login.js, I want to do so:
onLoginPressed = async () => {
let response = login(this.state.email, this.state.password)
if (response.status >= 200 && response.status < 300) {
//Login success
} else {
//Login error
}
}
But this doesn't seem to work. After I press login, nothing happens. Can anyone tell me where I am doing wrong.
Since login is an async function, and you want to wait for the response to be returned from login, you have to await the call to login too:
let response = await login(this.state.email, this.state.password)
login itself awaits for the fetch call to finish. So for you to wait for login to finish, you must await it. If you don't, login returns a promise, which as you observed, is not the response object from the request.

TypeError: Network Request Failed at XMLHttpRequest in react native app

I'm using react native fetch to make a post http request with graphql data to a graphql server endpoint. When starting up my graphql server and calling fetch with a POST in my react native app, I'm getting the following error:
TypeError: Network Request Failed at XMLHttpRequest in react native app
Request code
let graphqlServer = config.graphQLServerUrl;
const graphQLFetcher = (graphQLParams, requestType, token) => {
let body = null; //earlier i used var body =' '; //blank value --null & blank makes a different
let headers = null;
body = graphQLParams;
headers = {
'Accept': 'application/json',
'Content-Type': 'application/graphql',
'Authorization': 'Bearer ' + token
};
return fetch(graphqlServer, {
method: requestType,
headers: headers,
body: graphQLParams,
});
};
Data
qraphQLParams
query {
login(userName: ${credentials.userName}, passWord: ${credentials.passWord})
}
,
Any ideas?
I managed to get this to work by simply JSON.stringify the body of the request.
So..
graphQLParams = `query login{
login(input: {userName: "${obj.input.userName}", passWord: "${obj.input.passWord}" }) {
token
}
}
`
body = JSON.stringify({
query: graphQLParams
});