React Native fetch API cannot disable caching - react-native

I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. The server did not receive the request second time. I tried disabling cache with the following code.
export const mymails = (token) => {
return fetch(
API_URL+'?random_number='+ new Date().getTime(), {
method: 'GET',
headers: getHeaders(token)
})
.then(response => response.json());
};
getHeaders = (token) => {
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token='+token,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': 0
};
}
When I call the API through Postman client I see different result(not cached). I tried adding random number as parameter and setting cache control headers, but still returning cached result. Is there is anything else I could try.
Thanks

There must be a problem with how are you setting up the headers for fetching request.
Try with following,
You can follow the link for the same in the Official Fetch API
const mymails = (token) => {
var myHeaders = new Headers();
myHeaders.set('Accept', 'application/json');
myHeaders.set('Content-Type', 'application/json');
myHeaders.set('Authorization', 'Token token=' + String(token));
myHeaders.set('Cache-Control', 'no-cache');
myHeaders.set('Pragma', 'no-cache');
myHeaders.set('Expires', '0');
return fetch(
API_URL + '?random_number=' + new Date().getTime(), {
method: 'GET',
headers: myHeaders
})
.then(response => response.json());
};

Related

Downloading blob (zip) from one endpoint and uploading to different endpoint

I'm trying to download a zip from one endpoint and upload to another from a FE VueJS app, but it ends up corrupted on upload. I can do it with fileSaver but was hoping to skip the intermediate step of dropping it onto a HDD. If I download and POST it with Postman it works fine, so I suspect there's an issue with the responseType or blob type etc, but there's a lot of combinations & permutations. cURL works fine as well, but obviously not applicable here.
This is the code so far, the fetch code/config is from Postman, but how the uploaded file is stored/represented in Postman is opaque. The zipEndpointUp is an endpoint that consumes the file but it returns 'invalid archive'. localhost:8080 is proxied to the actual server to avoid CORs issues.
axios.get("http://localhost:8080/zipDirDown/download.zip, {
headers: {
Authorization: "Basic xxx",
mode: "no-cors",
responseType: 'arraybuffer',
}
}).then(res => {
const blob = new Blob([res.data], {type: "octet/stream"});
let myHeaders = new Headers();
myHeaders.append("Authorization", "Basic xxx");
let formData = new FormData();
formData.append("file", blob, "newZipFile.zip");
formData.append("name", "newZipFile Name");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formData,
redirect: 'follow'
};
fetch("http://localhost:8080/zipEndpointUp", requestOptions)
.then(response =>
response.text())
.then(result =>
console.log(result))
.catch(error =>
console.log('error', error));
})
So it turns out I needed to await the res promise (and change the Blob type):
fetch("http://localhost:8080/zipDirDown/download.zip, {
headers: {
Authorization: "Basic xxx",
responseType: 'arraybuffer',
}
}).then(res => {
const asyncBlob = await res.blob();
const blob = new Blob([asyncBlob], {type: "application/zip"});
})

How to set the request headers that i send in postman, but in the navigator?

In postman is a section where you can put or set a header. But how do i set it but in the navigator, that lasts over time through requests to different routes?
I´ve already tried setting a header, from the backend with differents methods like, and none of both worked:
res.header('x-token', jwt)
Or like
res.set('x-token', jwt)
And from the frontend i already tried with this methods and it didn´t work either:
const data = {id_token};
//let myHeaders = new Headers();
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(resp => resp.json())
.then(({jwt}) => {
if (jwt) {
localStorage.setItem('x-token', jwt);
//None of both worked
//myHeaders.append('x-token', jwt);
//myHeaders.set('x-token', jwt);
}
})
.catch(error => console.error('Error:', error))
This is the header that i wanna send to the different routes:
https://i.stack.imgur.com/ueoxu.png
You can set the x-token header from your screen shot like this:
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json',
'x-token': 'eyJhbGciOiJIUzl.....'
}
}).then(...).catch(...)

Empty response data for fetch call

react native fetch call (es5) returning undefined response. Here is the code of my fetch call.
body = {"username":"Gdgf","password":"dfgdfgdfg","remember":""}
var promise = new Promise(function(resolve, reject) {
fetch(`${FINAL_URL}users/login_app?app=1&submit=1`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// 'content-type': 'application/x-www-form-urlencoded',
// 'content-Type': 'multipart/form-data'
},
body: JSON.stringify(body),
})
.then(response => response.json())
.then(responseData => console.log('responseData', responseData)) // console output is --> responseData []
.catch(err => {
reject(err);
});
});
attaching the screnshot of postman too, to show that api is working.
Most of the time this problem occurs when you don't call your end point correctly. As you said in the comments, in the console log of ${FINAL_URL}users/login_app?app=1&submit=1 you missed the www, which makes the response undefined. If you still have a problem please delete new Promise section from the fetch.
I hope I could help.
Can you try changing the following line:
then(responseData => console.log('responseData', responseData))
to
then(responseData => console.log('responseData', JSON.stringify(responseData)))
What is the console output now?

How can I make a basic authorization with angular HttpClient and connect with an api Request?

well i have a problem i tried to connect an api with basic authorization but the server don´t give me access it return a 401(unautorized) my code is:
getApi() {
console.log('here i am in the method for get extensions');
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ***********************'
});
const options = {
headers,
withCredentials: true
};
// tslint:disable-next-line:max-line-length
return this.http.post('https://10.100.43.241/json', this.jsonBody, options).map((response: Response) => {
const resToJSON = JSON.stringify(response);
console.log('i am going to return jsonfrom method');
return resToJSON;
});
}
i tried too with postman an it is working as well. i really need to know how can i solved this problem of connection or authorization
note: i am not the administrator about the server
Try this architecture.
Component:
this._appApiService.getApi(this.jsonBody).subscribe(result => {
this.resToJSON = result;
});
Service:
getApi(jsonBody: any) {
// add authorization header with jwt token
let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.token });
let options = { headers: headers };
return this.http.post(this.baseUrl + 'https://10.100.43.241/json', this.jsonBody , options);
}

react-native fetch - request body - Unexpected EOF

in my react-native application, I'm trying to make fetch request with body. But, I get error message of unexpected EOF. Actually, the request is made, I mean I can see through backend logs that request is sent, whereas, right after the request, it shows error message.
Here is my fetch method.
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("SEND_SMS RESULT: ",responseJson);
})
.done();
here is the error screen I get.
I would say that it fails on this line: response.json()
Are you sure that your response is a valid JSON?
Try testing the response with Postman or add .catch(e => console.log(e)) before done();
var Url = "https://----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'number': '11111111-'})
})
.then((response) => response.text())
.then((responseJson) => {
const resposeJson2 = responseJson.length ? JSON.parse(responseJson) : {};
console.log("SEND_SMS RESULT: ",responseJson2);
})
.done();
Your server is returning null instead of error and unfortunately response.json() cant operate on null response
you can research briefly on it the keywords are "Handling null response from api"