Data sent from flask not received from react - html

I'm using flask as the backend and the database is using firebase. I want to get the data sent by app.py from React, but it keeps failing.
app.py
#app.route("/StoreListView")
def list_stores():
storedata = DB.get_store() #read the table
tot_count = len(storedata)
return render_template(
"index.html",
storedatas=storedata.items(),
total=tot_count)
StoreListView.js
function Stores(){
useEffect(() => {
fetch("/StoreListView", {
headers: {
Accept: "application/json",
}
})
.then(response => response.json())
.then(jsonData => {
console.log(jsonData)})
.catch(
(err) => console.log(err))
}, [])
}
I see this error.
SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
I think it's a problem to render html in the list_stores function... but if I just do the return stored data, the front screen coded with the react does not come out and the data is just printed out...

Related

Api GET request returns an empty response but postman does not

I am trying to make an api call to a remote server, Initially, I got this error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I temporarily solve this error by attaching the https://cors-anywhere.herokuapp.com link before the link, or sometimes using the Moesif Cors-Any-where chrome extension. The fetch now returns 200 ok status but the response is empty.
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
response: {}
data: undefined
However, if I run the same query on postman, it returns the expected response json object. How do I fix this?
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then(response => {
if (response.ok) {
console.log(response)
return response
}
else
console.log(`Looks like something went wrong. Status: ${response.status}`)
})
.then(response => {
response.json()
console.log("response: " + JSON.stringify(response))
})
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
response.json() returns a promise, you have to wait for resolving this. you also have to return something if you want the next then in the chain to receive something.
something like this should work:
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then((response) => {
if (response.ok) {
return response
} else {
throw `Looks like something went wrong. Status: ${response.status}`;
}
})
.then(response => response.json())
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
or with your console.log:
return response.json().then((data) => console.log(data));
Add A Header For accept all as follow in the front-end request
if you want to request data from a server it has to be on the same domain, or the 'Access-Control-Allow-Origin' header has to be set.
I wont rely on a service like https://cors-anywhere.herokuapp.com
For development you can use a proxy server to bypass this limitation. (many frameworks already have a solution for this, i don't know which one you use)
I know this is a very old question, but I've got exact same problem last night. The issue was the SSL connection, which is enforced by Chrome and is not enforced by Postman. So just make sure your API can handle https protocol.

Feathersjs socketio how to correctly set params.route?

I have a Feathersjs API which using REST can serve a GET request to a URL like http://server.com/service-name/:fieldName where fieldName has a string value. The API assigns the value of fieldName to params.query.
While developing a React Native app, I am trying to make the same request using feathers socketio client. The request looks like this:
return this.app.service('service-name/:fieldName').find({
query:{fieldName='value'}
}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
The request above makes it to the server, but the value of fieldName is either undefined or some other unwanted value because the server returns an empty result set. I have also read that the setSlug hook would be an option, but I am not sure how to do it.
Can someone please help me resolve this issue by sending the real value of fieldName in the request to the server?
[Edit]
After checking the logs on the API server, I found out that a REST API request has the correct params.route object:
object(9) {
["query"] => object(0) {}
["route"] => object(1) {
["fieldName"] => string(5) "value"
}
...
The params.route is empty with the socketio request:
object(9) {
["query"] => object(0) {}
["route"] => object(0) {}
["connection"] => object(6) {
["provider"] => string(8) "socketio"
["payload"] => object(1) {
["userId"] => number(3)
}
...
While I'm relieved to know where the problem is, would anyone please tell me how to correctly set params.route in React Native using a socketio request?
You can use a normal route just like with HTTP which will set params.route with fieldName:
return this.app.service('service-name/something').find({}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
Will set { params: { route: { fieldName: 'something' } } }

How to convert XML to JSON with react

I have an API that provides me XML data, and i want to convert that XML data from the API into JSON. Can anyone help me wiht that problem?
I'm using Expo to creat a app. I tried to use nodemoduls, but when i tried that I alwas get an error "It failed because React Native does not include the Node standard library" The code belwo dosen't work
import { View, Text, ActivityIndicator } from 'react-native'
import { fetch } from "fetch";
const furl = 'https://skimap.org/Regions/view/346.xml';
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson({attributeMode: true});
export default class RegionList extends PureComponent {
state = { regions: [] };
async componentWillMount() {
fetch(furl).then(response => parser.xmlToJson(response, (err,json)=>{
if(err){
console.log(err);
}
}))
.then( (response) => this.setState({regions: response}));
}
Try this:
import {Xml2Json} from 'react-native-xml-to-json';
fetch(furl).then(response =>
Xml2Json.toJson(response, data => {
console.log("Data = ", data);
}).then( (response) => this.setState({regions: data})
);

400 error for api call in react redux working fine in an example

I am trying to learn react redux api call
so I took an example and implemented in stackblitz but I am getting the below error
GET https://newsapi.org/v1/articles?%20%20%20%20%20%20%20source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc 400 (Bad Request)
can you tell me how to fix it
providing my code and stackblitz below
https://medium.com/#lavitr01051977/basic-react-redux-app-with-async-call-to-api-e478e6e0c48b
https://stackblitz.com/edit/react-redux-realworld-4ldsnt?file=components/ChannelsField.js
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?
source=${channel}&apiKey=${MY_API_KEY}`)
.then(
response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},
);
};
}
It looks like your request has extra spaces (%20) between ? and source which is causing the 400 bad request. Change your function to the following and it should work:
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?source=${channel}&apiKey=${MY_API_KEY}`)
.then(response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},);
};
}
Here is the same GET request without the spaces:
https://newsapi.org/v1/articles?source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc

React failing to parse a JSON object from server

I'm running into this error:
Uncaught (in promise) SyntaxError: Unexpected token [ in JSON at position 1
when I pass a JSON object containing an array of JSON objects to my component. The object structure is:
{ "arrayName": [{object},{object},{object}, etc...] }
I've run the JSON through a validator and it comes up clean but my api call always returns the same error.
export const api = 'http://localhost:8000'
export const headers = {
'Content-Type': 'application/json',
'Accept' : 'application/json',
}
export const getAll = () =>
fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
This is where it gets called in App.js:
componentDidMount() {
eventsAPI.getAll().then((events) => {
console.log(events)
this.setState({ events })
})
}
I'm not sure why I'm getting the error, I know I'm sending a valid JSON object, is the way I'm receiving it wrong? I can see in the network tab of the dev tools that the correct format is being passed and received. I just don't know where exactly I've gone wrong. This is the response logged from the server. I can see the XHR response in dev-tools but it's a bit big to post here 25+ objects.
You need to modify getAll to actually return something. As it is a fetch, you can just return that, which will return the promise.
export const getAll = () =>
return fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
Now wherever you use getAll be sure to call then:
getAll().then(data => console.log(data))