I'm trying to build a react-native app with expo and while trying to sign up I get the following error message stemming from my api.js file:
response.text is not a function. (In 'response.text()', 'response.text' is undefined).
Here is my code:
const BASE_URL = "my local IP:5000";
export const api = async (url, method, body = null, headers = {}) => {
try {
const endPoint = BASE_URL.concat(url);
const reqBody = body ? JSON.stringify(body) : null;
const fetchParams = {method, headers};
if((method === "POST" || method === "PUT") && !reqBody) {
throw new Error("Request body required");
}
if(reqBody) {
fetchParams.headers["Content-type"] = "application/json";
fetchParams.body = reqBody;
}
const fetchPromise = fetch(endPoint, fetchParams);
const timeOutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject("Request Timeout");
}, 3000);
});
const response = await Promise.race([fetchPromise, timeOutPromise]);
return response;
} catch (e) {
return e;
}
}
export const fetchApi = async (url, method, body, statusCode, token = null, loader = false)
=> {
try {
const headers = {}
const result = {
token: null,
success: false,
responseBody: null
};
if(token) {
headers["x-auth"] = token;
}
const response = await api(url, method, body, headers);
console.log(response);
if(response.status === statusCode) {
result.success = true;
if(response.headers.get("x-auth")) {
result.token = response.headers.get("x-auth");
}
Here is response.text()
let responseBody;
const responseText = await response.text();
//const responseText = await response.json();
try {
responseBody = JSON.parse(responseText);
} catch (e) {
responseBody = responseText;
}
result.responseBody = responseBody;
return result;
}
Here is response.text()
let errorBody;
const errorText = await response.text();
//const errorText = await response.json();
try {
errorBody = JSON.parse(errorText);
} catch (e) {
errorBody = errorText;
}
result.responseBody = errorBody;
console.log(result);
throw result;
} catch (error) {
return error;
}
}
Any help would be immensely appreciated.
Related
How to return a Promise from the multiple axios get requests?
I have below code.
async function main() {
const URL_1 = 'abc.com/get1/data1';
const result_1 = await getData(URL_1);
const URL_2 = 'abc.com/get2/data2';
const result_2 = await getData(URL_2);
}
async function getData(dataURI) {
let getURI = dataURI;
const config = {
headers: {
Authorization: `Bearer ${my-token-text}`,
},
};
var finalData = [];
// until we get the next URL keep sending the requests
while (getURI != null) {
try {
const getResult = await axios.get(getURI, config);
if (getResult.status === 200) {
const receivedData = getResult.data.value;
finalData.push(...receivedData);
// check if we have nextLink in the payload
if (Object.prototype.hasOwnProperty.call(getResult.data, 'nextLink')) {
getURI = getResult.data.nextLink;
} else {
getURI = null;
return finalData;
}
}
} catch (err) {
break;
}
}
return null;
}
What I am trying to achieve is:
async function main() {
const URL_1 = 'abc.com/get1/data1';
const result_1 = getData(URL_1);
promisesArray.push(result_1);
const URL_2 = 'abc.com/get2/data2';
const result_2 = getData(URL_2);
promisesArray.push(result_2);
await Promise.allSettled(promisesArray).then((results) => {
console.log('Promise All Done: ', results);
});
}
This why I can perform all the requests in parallel.
But when I update the function getData(dataURI) to return return new Promise then I get error for await axios.
async function getData(dataURI) {
return new Promise((resolve, reject) => {
// Same code as above
});
}
I get error:
SyntaxError: await is only valid in async function
As Promise is not async I cannot await in the Promise.
Have you tried:
return new Promise(async (resolve, reject) => {
// Same code as above
});
I have an assignment to complete a function that makes API requests using a name. This request will return a json object and this object has a 'height' field that the function should return. I tried but my solution odes not seem to work. Below is my code. Can someone point me in the right direction?
async function getHeight(name) {
let url = "sample url"
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
let result = (JSON.parse(data));
let result_data = result[data];
if(result_data == null){
return -1
} else{
let cataJson = (JSON.parse(result_data));
return cataJson["height"];
}
});
}).on("error", (err) => {
return -1;
});
}
async function getHeight(name) {
let url = "sample url"
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
this code should be some thing like what you need.
you make a get request to the url then you parse the given data to json format then the function returns that data.
You can use fetch with promise like this.
async function getHeight(name) {
return new Promise((resolve, reject)=>{
let url = "sample URL"
fetch(url)
.then(res=>res.json())
.then(data=>{
let result = (JSON.parse(data));
let result_data = result[data];
if(!result_data)resolve(-1)
else resolve((JSON.parse(result_data)).height)
})
.catch(e=>{reject()})
})
}
And to call the function
async function main(){
try{
var height = await getHeight("John");
console.log(height)
}catch(e){
console.log("Error Fetching height")
}
}
main()
const getHeight = async (name) {
let url = "url"
try {
let res = await fetch(url,{
method: "GET"
);
if (res.ok == true) {
return await res.json();
} else {
throw new Error("error")
}
} catch (error) {
console.log(error);
}
}
When I try to set a value via AsyncStorage.getItem(), I cannot request it back.
let tokenData = null;
const getData = async () => {
let token;
try {
token = await AsyncStorage.getItem('token');
tokenData = JSON.parse(token);
} catch (e) {
// error reading value
}
};
I have set item like follows
const setLoginLocal = async loginData => {
try {
let token = loginData.headers.authorization;
let headerToken = ['token', JSON.stringify(token)];
let user = ['user', JSON.stringify(loginData.data)];
await AsyncStorage.setItem([user, headerToken]);
} catch (err) {
console.log(err);
}
};
If you want to store data you have to setItem like this:
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
then you can retrieve it with getItem like this:
const getData = async key => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};
const setLoginLocal = async loginData => {
try {
let token = loginData.headers.authorization;
let headerToken = ['token', JSON.stringify(token)];
let user = ['user', JSON.stringify(loginData.data)];
await AsyncStorage.setItem([user, headerToken]);
} catch (err) {
console.log(err);
}
};
i want this function to return either true or false, instead I get
/**
* Sends request to the backend to check if jwt is valid
* #returns {boolean}
*/
const isAuthenticated = () => {
const token = localStorage.getItem('jwt');
if(!token) return false;
const config = {headers : {'x-auth-token' : token}};
const response = axios.get('http://localhost:8000/user' , config)
.then(res => res.status === 200 ? true : false)
.catch(err => false);
return response;
}
export default isAuthenticated;
I tried separating them and using async/await :
const isAuthenticated = async () => {
const response = await makeRequest();
return response;
}
const makeRequest = async () => {
const token = localStorage.getItem('jwt');
const config = {headers : {'x-auth-token' : token}};
const response = await axios.get('http://localhost:8000/user' , config)
.then(res => res.status === 200 ? true : false)
.catch(err => false);
return response;
}
And still the same..
After some suggestions :
const isAuthenticated = () => {
const response = makeRequest();
return response;
}
const makeRequest = async () => {
try {
const token = localStorage.getItem('jwt');
const config = {headers : {'x-auth-token' : token}};
const response = await axios.get('http://localhost:8000/user', config);
if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
console.log('success stuff');
return true;
}
return false;
} catch (err) {
console.error(err)
return false;
}
}
export default isAuthenticated;
First of all if.
If you are using the default promise then & catch, then the success action should be handled within the 'then' function.
axios.get('http://localhost:8000/user', config)
.then(res => console.log('succesfull stuff to be done here')
.catch(err => console.error(err)); // promise
if you want to use the async/await syntactic sugar, which I personally like it's
const makeRequest = async () => {
try {
const token = localStorage.getItem('jwt');
const config = {headers : {'x-auth-token' : token}};
const response = await axios.get('http://localhost:8000/user', config);
if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
console.log('success stuff');
return true;
}
return false;
} catch (err) {
console.error(err)
return false;
}
}
You have to employ the use of async/await,like this:
const isAuthenticated =async () => {
const token = localStorage.getItem('jwt');
if(!token) return false;
const config = {headers : {'x-auth-token' : token}};
const response =await axios.get('http://localhost:8000/user' , config)
.then(res => res.status === 200 ? true : false)
.catch(err => false);
return response;
}
I have two methods:
Gets a photo with an ID
Gets a collection of photos with an ID
I'm trying to get the response data to pass into the savePhoto() method so I'm able to trigger the download.
So far I've had no look, no matter what I try.
Any and all advice/feedback would be helpful.
Thank you.
Attempt 1
const unsplashAxios = require('./unsplashAxios');
const fs = require('fs');
const request = require('request');
class Unsplash {
constructor() {
this.unsplash = null;
}
getPhoto(id){
this.unsplash = unsplashAxios( `/photos/${id}`);
this.unsplash.then((response) => {
console.log(response.data)
}).catch((response) => {
console.log(response);
});
return this;
}
getCollection(id){
this.unsplash = unsplashAxios(`/collections/${id}/photos`);
this.unsplash.then((response) => {
console.log(response.data)
}).catch((response) => {
console.log(response);
});
return this;
}
savePhoto() {
// Get response data
// const imgUrl = data.urls.raw;
// const imgPath = `${data.id}.jpg`
request('https://images.unsplash.com/photo-1571111937090-4452a4af8755?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEwNjE4NH0').pipe(fs.createWriteStream('eyJhcHBfaWQiOjEwNjE4NH0.jpg'));
}
}
myUnsplash = new Unsplash();
myUnsplash.getPhoto('PgHc0Ka1E0A').savePhoto();
myUnsplash.getCollection('62890').savePhoto();
Attempt 2
const unsplashAxios = require('./unsplashAxios');
const fs = require('fs');
const request = require('request');
class Unsplash {
constructor() {
this.unsplash = null;
}
async getPhoto(id) {
try {
this.unsplash = await unsplashAxios(`/photos/${id}`)
const response = this.unsplash
savePhoto(response)
} catch (error) {
console.error(error)
}
return this;
}
async getCollection(id) {
try {
this.unsplash = await unsplashAxios(`/collections/${id}/photos`)
const response = this.unsplash
savePhoto(response)
} catch (error) {
console.error(error)
}
return this;
}
savePhoto(response) {
console.log(response)
// Get response data
// const imgUrl = data.urls.raw;
// const imgPath = `${data.id}.jpg`
//request('https://images.unsplash.com/photo-1571111937090-4452a4af8755?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEwNjE4NH0').pipe(fs.createWriteStream('eyJhcHBfaWQiOjEwNjE4NH0.jpg'));
}
}
myUnsplash = new Unsplash()
myUnsplash.getPhoto('PgHc0Ka1E0A')
myUnsplash.getCollection('62890')