How to get Html code by fetching web API response? - react-native

When we are trying to fetch html code via fetch API response but we are enable to get it because it return "Unexpected Token <"
onLoginService2 = async () => {
try {
var hittingURl = "https://members.iracing.com/membersite/Login?username=dave#rms55.com.au&password=rms55Pa55&utcoffset=-600&todaysdate=1558055491688&checkbox=0";
const myRequest = new Request(hittingURl.toString(),
{
method: 'POST',
headers: {
'Accept': 'text/html',
'Content-Type': 'text/html;charset=ISO-8859-1',
},
timeout: 1000,
// body: JSON.stringify("")
}
);
fetch(myRequest)
.then((response) => console.log("abcdefghijklmon--> "+JSON.stringify(response)))
.then((data) => {
console.log("RESPONSERR----> ",data+"");
// this.setState({ isLoading: false })
// this.onLoginSuccessFull(responseJson)
})
.catch((error) => {
this.setState({ isLoading: false })
console.log("response--31" + error);
})
} catch{
}
// }
}

The response of first then has a method .text(), which return Promise
Try this
fetch(myRequest)
.then(resp => resp.text())
.then(text => {
//text is html
})
*Just copy the above and run in console to see the result.

Related

How do I use Async Storage to save Data Locally after calling fetch in react native?

I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

How to upload a file in react-native iOS?

While trying to upload a file I ran into an issue on iOS, the code works fine on android. After a bit of googling, I found that it is a known issue in react-native iOS and has a bug report submitted. This is the issue. I want to know if there is any other way to upload files on iOS. Below is the snippet of code I'm using. Please let me know if there is something that can be done.
const resp = await fetch(uploadUrl, {
method: 'POST',
headers: {
'content-type': 'multipart/form-data',
},
body: file, // file is File type
});
You can something like below code snippet
function uploadProfileImage(image, token) {
const url = ServiceUrls.UPLOAD_PROFILE_IMAGE
return uploadResourceWithPost({
url,
authToken: token,
formData: createFormData(image),
})
}
const createFormData = (data) => {
const form = new FormData()
form.append('file', {
uri: Platform.OS === 'android' ? data.uri : data.uri.replace('file://', ''),
type: 'image/jpeg',
name: 'image.jpg',
})
return form
}
const uploadResourceWithPost = ({ url, authToken, formData }) => {
return handleResponse(axios.post(url, formData, defaultUploadOptions(authToken)))
}
const defaultUploadOptions = (authToken) => ({
timeout,
headers: {
'X-Auth-Token': authToken,
'Content-Type': 'multipart/form-data',
},
})
const handleResponse = (responsePromise) => {
return NetInfo.fetch().then((state) => {
if (state.isConnected) {
return responsePromise
.then((response) => {
return ResponseService.parseSuccess(response)
})
.catch((error) => {
return ResponseService.parseError(error)
})
}
return {
ok: false,
message: 'Check your network connection and try again.',
status: 408,
}
})
}
const parseSuccess = ({ data, headers }) => ({ ...data, headers, ok: true })
const parseError = ({ response }) => {
let message = 'Check your network connection and try again.'
let status = 408
if (response && response.data) {
const { data } = response
message = data.message
status = data.code
}
return { status, message }
}

Using Axios to retry request after refreshing JWT token in Vuex store

I'm trying to use Axios to retry failed requests due to JWT expiry
So far I have then following request in a method on a Vue component:
getAPI2.get("/api/v1/sessions/",{ headers: headers }).then(response => {
console.log(response);
this.items = response.data.items;
});
This is using the below interceptor when it hits an error
const getAPI2 = axios.create({
baseURL: '/'
})
getAPI2.interceptors.response.use(response => response, err => {
if (err.config && err.response && err.response.status === 401) {
store.dispatch('refreshToken')
.then(access => {
axios.request({
method: 'get',
headers: { Authorization: `Bearer ${store.state.accessToken}` },
url: err.config.url
}).then(response => {
console.log('Successfully got data')
console.log(response)
return response;
}).catch(err => {
console.log('Got the new access token but errored after')
return Promise.reject(err)
})
})
.catch(err => {
return Promise.reject(err)
})
}
})
I'm seeing the data when the request hits an error and goes through the interceptor but I think there's an issue in passing back the response to my component
Apologies if this is obvious, my javascript knowledge is in its infancy
After some playing around I managed to get this working:
const getAPI3 = axios.create({
baseURL: '/'
})
getAPI3.interceptors.response.use( (response) => {
// Return normal response
return response;
}, (error) => {
// Return non auth error
if (error.response.status !== 401) {
return new Promise((resolve, reject) => {
reject(error);
});
}
return store.dispatch('refreshToken')
.then((token) => {
// Make new request
const config = error.config;
config.headers = { Authorization: `Bearer ${store.state.accessToken}` }
return new Promise((resolve, reject) => {
axios.request(config).then(response => {
resolve(response);
}).catch((error) => {
reject(error);
})
});
})
.catch((error) => {
Promise.reject(error);
});
});

upload mp4 with expo in react native problem

I'm new in react native and this might be a silly question, but when I'm trying to upload .mp4 with react native using expo in my backend server side (laravel) I receive a jpg/jpeg file which is weird because with the same code when I try to upload .mov file it works as expected without any problem.
is there anything I've done wrong?
p.s: I've already tried to fetch method and axios but I get the same result with both.
here's my code:
postForm = () => {
var body = new FormData();
body.append("title", this.state.text);
body.append("description", this.state.description);
body.append("category_id", this.state.category_id);
body.append("type", this.state.type);
body.append('media_path', {
uri: this.state.photos.photos[0].file,
name: `media.mp4`,
type: this.state.format
});
this.state.photos.photos.map((item, index) => {
console.log("addable item is", index, item.file);
//skip first photo to media_path
if (index == 0) {
console.log("avalin index: ", item.file)
return
}
else {
file = item.file.toLowerCase();
console.log("full name is", file);
let addable = {
uri: item.file,
name: `addables`,
type: this.state.format
}
body.append("addables[]", addable)
}
})
console.log("final body: ", body);
this.setState({
uploading: true,
}, function () {
let apiUrl = `${config.BASE_URL}api/products`;
console.log(apiUrl);
axios({
method: 'POST',
url: apiUrl,
data: body,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
"authorization": this.state.token
}
})
.then((response) => {
//handle success
console.log("success response: ", response);
if (response.data.status == true) {
this.setState({
uploading: false
}, function () {
this.props.navigation.push('profile');
})
}
else {
this.setState({
uploading: false
}, function () {
this.showToast("unsuccessful operation.", "danger", 3000);
})
}
})
.catch(function (response) {
//handle error
console.log(response);
alert("response)
});
})
}
and this is what laravel logs tels me:
array (
'title' => 'test',
'description' => 'test',
'category_id' => '3',
'type' => 'video',
'media_path' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'media.mp4',
'mimeType' => 'image/jpeg',
'error' => 0,
'hashName' => NULL,
)),
)

fetch response.json() gives responseData = undefined

When using fetch:
fetch(REQUEST_URL, {
method: 'get',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) =>
{
response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
console.log(responseData);
});
}).catch(function(err) {
console.log(err);
})
.done();
The following works works, do you know why? :
JSON.parse(response._bodyText)
The chaining response should look more like this, specifically the response.json part. Then you should get an Object back in console.log.
.then(response => response.json())
.then(response => {
console.log(response)
}
Fetch is a little hard to get your head around. I am new to this so dont shoot me down if flames here but response data is another promise and you need to return response data and then handle that promise with yet another then statement where you can finally log the response, also your are missing some return statements in your promises:
var makeRequest = function(){
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
return response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
addTestToPage(responseData.title);
return responseData;
})
.catch(function(err) {
console.log(err);
})
}
function addTestToPage(textToAdd){
var para = document.createElement("p");
var node = document.createTextNode(textToAdd);
para.appendChild(node);
var element = document.getElementsByTagName("body")[0];
element.appendChild(para);
}
makeRequest();
hope that helps see: https://jsfiddle.net/byz17L4L/
Here's how it finally worked out in my case:
fetch('http://localhost:3001/questions', {
method: 'GET',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
.then(response => { return response.json();})
.then(responseData => {console.log(responseData); return responseData;})
.then(data => {this.setState({"questions" : data});})
.catch(err => {
console.log("fetch error" + err);
});
}
because you didn't return response.json() in the first then.
import React, {useEffect} from 'react';
useEffect(() => {
getRecipes();
}, []);
const getRecipes = async () => {
const response = await fetch(
`https://........`
);
const data = await response.json();
console.log(data);
Use this method You can easily fatch data.
fetch(weatherIng + zipCode +apiKey)
.then(response => response.json())
.then(response => {
console.log(response.main);
this.setState({
weather: ((response.main.temp * (9/5))-459.67).toFixed(0),
humidity:((response.main.humidity * (9/5))-459.67).toFixed(0)
})
It will think that you are trying to declare something if you don't enclose it in its own:
.then(response => {
console.log(response.main);
}) . " around the this.setState