keeps fetching the old json data? - json

I'm trying to fetch a json file from a https link however, no matter what link a give the result does not change!?
I validated all the json files. in case they had an error.
the responseData stays the same, and even when I force the data to change by instead returning responseData returning a json manually written; it changes right back to the old json data that just doesnt change when I return responseData back.
And the responseData that I requested to be be posted on the console gives the wrong information
The url given is correct.
but the output doesnt correspond to the data when I fill the link in the internetbrowser.
constructor(props){
super(props);
this.state = {
connected: false,
}
this.init = this.init.bind(this);
this.getJson = this.getJson.bind(this);
this.updateVisited = this.updateVisited.bind(this);
}
init = async ({json})=>{
if(json==null){
await AsyncStorage.setItem('database', "");
alert('error occured');
} else {
await AsyncStorage.setItem('database', JSON.stringify(json));
this.setState({
connected: true
});
}
}
getJson = async ()=>{
var url = await AsyncStorage.getItem("database_url");
console.log(url);
return fetch(url,
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseData => {
this.updateVisited(url);
console.log(responseData);
return responseData;
})
.catch(error => {
alert('Could not connect!');
return null;
})
}
connect = async ({url})=>{
await AsyncStorage.setItem("database_url", url);
this.getJson().then(json => this.init({json}));
}
"a_json": [{"name": "greg"}]
"test": [{"name": "sheldon"}]
"temp": [{"name": "bob"}]
when the url points to the json test it gives bob expecting sheldon
when the url points to the json temp it gives bob expecting bob
when the url points to the json a_json it gives bob expecting greg
when returning a json without trying to fetch it from the internet at the place of responseData; it gives the expecting value
If you need more information, feel free to ask.
Thank you for your time reading my question.

The problem was the Cache-Control.
I added 'Cache-Control': 'no-cache' to the header of the fetch, which fixed the problem!
This was pointed out by #Pritish Vaidya in the comments

Related

how to fetch large json from a post in angular6/7

I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}

How to get a value from returned JSON in HTML?

My client side looks like this:
filename="random_filename.docx"
var response = await fetch("https://backend.wl.r.appspot.com/scriptstuff", {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ file: filename })
});
var data = response.json();
console.log(data);
and my backend return looks like this
response = jsonify({'prediction': str(prob)})
response.headers['Access-Control-Allow-Origin'] = '*'
return response, 200
I receive a promise with the value of 'prediction', but I'm not sure how to access that or why the current code isn't working.
EDIT: adding await before response.json() works
You can execute a function upon a promise being fulfilled by appending a .then() to the fetch request. If you're already receiving the JSON object then the values can be accessed by data.some_key.
I'm not an expert but first store str(prob) into a variable and then create an object with it. I think jsonify() takes things very literally.

I need to fetch API to get a raw value from response same as the result in POSTMAN but fail?

I am new from here. Just stuck on some problem of fetching the data from frontend(react) to the raw value in JSON. For the login part, when I enter the email and password, supposedly the response are same as the result in POSTMAN, but i get the error. I am figure out this issue for almost oneweek. I would be appreciate for those who help me to solve on this issue. I will elaborate further on below about my situation:
Here is the response of API from postman (supposedly I should get this response):
The result I get in the browser:
Source Code:
constructor (props){
super(props);
this.state ={
loginEmail: '',
loginPassword: ''
}
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
login(){
PostData('api/users/login', this.state).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
});
}
PostData:
export function PostData(type, userData = {}){
let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"
return new Promise((resolve, reject) => {
fetch(BaseUrl+type,{
method: "POST",
body: JSON.stringify(userData),
Accept: 'application/json',
// headers:{
// 'Content-Type': 'application/json'
// }
}).then(res => res.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error)=>{
console.error('Error:', error);
})
});
}
Commend down here if anyone of you need more code.
The problem is you need to allow CORS.
You can read more about CORS in here

JSON response react native Post method problem

I am facing a strange problem, I am using Nexmo to verify number, and I am sending a post method
fetch('http://monasabat-app.com/basta_app/sign_up.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).then((response) => response.json())
.then((responseJson) => {
const ss1 = responseJson.status[0]
console.log(ss1)
let success = 'success'
if(ss1.status === success){
alert(ss1.status)
this.props.navigation.navigate('verNum',{
uid:ss1.uid,
phone:this.state.phone,
name:this.state.name,
emai:this.state.email
})
}else{
alert(ss1.status)
}
The sign up info(formBody) is successfully stored in the database but it doesn't navigate to the verNum screen neither alert the ss1.status but if the response is not success it does alert ss1.status in the else part (num is already registered) so I guess the problem is in the if condition part but the strange thing it does work sometimes and it doesn't some other times with a warning Possible Unhandled Promise Rejection (id: 1).
My JSON response
{
"status": [
{
"status": "success",
"uid": "99"
}
]
}
First, check if the this.props and this.state is accessible inside the promise.
If not before fetch create a variable that takes the value of this
Example let self = this;
then
this.props.navigation.navigate
would become
self.props.navigation.navigate.

Aurelia typescript load json service

I am trying to create a class that will have two functions:
1) Load items from a json stored in my local server and return that variable with all the items.
2) Return a single item by id.
The problem is I want to use these two methods from different modules, and I do not know how to go about implementing the module and using it. So far, I have been able to implement the http part with aurelia's fetch client, but I don't know how to make the function:
function getItems() {
// some http request code
return fetchedItems;
}
Because the code in aurelia.io does something like this (which I have tried and actually works if I print the data):
import 'fetch';
import {HttpClient} from "aurelia-fetch-client";
export function getItems(url) {
let client = new HttpClient();
client.configure(config => {
config
.withBaseUrl('api/')
.withDefaults({
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
});
});
client.fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
});
}
All this works ok. The point is that instead of doing 'console.log(data);' I want to return it, but so far the only thing that seems to work is assigning the returned items to a local class variable with 'this.items = data'. I would be ok with this so long as I get a function that allows to do this:
let items = getItems();
And
let item = getItemById(id);
EDIT: SOLVED
Users should note that, in order for this to work, they should have this in their tsconfig.js:
"target": "es6"
Because async/await requires at least ES2015.
Use async / await
If you're using TypeScript and targeting ES6, you can use the await/async keywords.
export async function getItems(url) {
let client = new HttpClient();
client.configure(config => {
config
.withBaseUrl('api/')
.withDefaults({
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
});
});
return await client.fetch(url)
.then(response => response.json());
}
client.fetch returns a promise, so you just have to return it:
return client.fetch(url)
.then(response => response.json());
To use the function:
getItems(url)
.then(data => this.someProperty = data);