TypeError: Network Request Failed at XMLHttpRequest in react native app - react-native

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

Related

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")}`,
}

The body parameters are not working in fetch post react native

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

GET request works in postman but fails with Axios

I'm sending GET request to the same endpoint with the same headers, including the Bearer, but while i get 200 and the correct JSON as a result when calling from Postman, when i send the request using Axios in my (Vue) project i get 302.
the call from the local project , running on localhost:8080 (in case its useful) is as follows:
const { authToken, userID } = store.getters.authUser
const config = {
method: 'get',
url: '/' + userID,
headers: {
Authorization: `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
}
axios(config)
.then(res => {
console.log(res)
return res
})
.catch(e => {
console.log(e)
})
while in postman all i do is create a GET request with the same url and all i add in the headers is the 'Bearer ...'
the error i get from axios is :
Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:87)
and response status is 302 , any idea whats going on here??
both values of userID and the authToken exists and are equal to the same values i used with postman, same goes for the url

Ionic-native HTTP POST method not working on iOS (but perfectly working on Android)

I'm using #ionic-native/http in my Ionic 4 project for logging in user by sending body with UserId and Password and header with 'Content-Type': 'application/json' through POST method. Its working fine in android and but on iOS it responding with a http 400 error.
Dependencies:
"#ionic-native/http": "^5.3.0",
"cordova-plugin-advanced-http": "^2.0.9",
I tired using the #angular/http but its giving a CORS error on browser, android and iOS. And I can't change the server side code to enable CORS.
Code:
import { HTTP } from '#ionic-native/http/ngx';
// Login method
async login(userId, password) {
// login user
const httpBody = {
'UserId': userId,
'Password': btoa(password)
};
const httpHeader = {
'Content-Type': 'application/json',
};
const user = await this.http.post(this.loginURL, httpBody, httpHeader);
return JSON.parse(user.data);
}
Expected result response with StatusCode 200
Actual Result response with StatusCode 400
I waas having the same issue; in my case I fixed it by
setting the data serializer to 'utf8' and by setting the Content-Type header to 'application/x-www-form-urlencoded'
this.http.setDataSerializer('utf8');
const httpHeader = {
'Content-Type': 'application/application/x-www-form-urlencoded'
};

Post to /upload from react native

I'm trying to upload a picture to strapi from react native.
async function uploadPicture(uri) {
var data = new FormData();
data.append('files', {
uri: uri.replace('file://', ''),
name: uri,
type: 'image/jpg'
});
// Create the config object for the POST
// You typically have an OAuth2 token that you use for authentication
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data;'
},
body: data
};
const fetchPromise = fetch('http://<host>:1337/upload', config)
console.log(fetchPromise)
return await fetchPromise
}
I get a 200 status code but no new picture is listed on the uploads page.
Oh! I figured it out using simple-http-upload-server to test the uploads. The problem was that I was setting the name of the file to be the uri. This would probably cause an error on strapi when creating the file on the server folder. It should return an error code nonetheless.