working with react and flask python making api request and render them in react simple code example
Example 1: why fetch from react to flask back end not working
//There are some packages you can use like fetch-with-proxy or node-https-proxy-agent, fetch-with-proxy can get HTTP_PROXY env var to set proxy, and you can use the other create proxy agent.
//But I recommend that to use other package to send request like axios.
import axios from 'axios';
const axios_ = axios.create({
baseURL: 'http://localhost:5000',
headers: { 'Content-Type': 'application/json' },
})
class App extends React.Component {
componentDidMount() {
axios_.get('/')
.then(response => {
console.log(response.text()) //Here is the text() i said before
this.setState({ snippets: response.data })
})
.catch(error => {
console.log(error)
});
}
...}
Example 2: why fetch from react to flask back end not working
Latest update: Sorry about I misunderstood about proxy in nodejs, and fetch() can support this kind of proxy.
//After I do some trial and error, you just need to change you path '/' to '/something_else' and the proxy work well.
//Wrong information:
//This is not issue about python and flask.
//You use fetch() in javascript, and this is native js function, so it is not related with proxy you set in package.json.
//If you want to use fetch() to get other port, you have to give it the whole url http://localhost:5000/ or you will get the same port of you react app.
fetch('http://localhost:5000/')
.then(response => {
console.log(response.text()) //Here is the text() i said before
this.setState({ snippets: response.data })
})
.catch(error => {
console.log(error)
});