I'm trying to fetch data returned from url. Curl to the url results in following:
[{"name": "Hello World!"}]
Following is the code in my App.js
import React, { Component } from 'react';
import Contacts from './components/contacts';
class App extends Component {
render() {
return (
<Contacts contacts={this.state.contacts} />
)
}
state = {
contacts: []
};
componentDidMount() {
fetch('url')
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(console.log)
}
}
export default App;
My contact.js contains the following:
// src/components/contacts.js
import React from 'react'
const Contacts = ({ contacts }) => {
return (
<div>
<center><h1>Contact List</h1></center>
{contacts.map((contact) => (
<div class="card">
<div class="card-body">
<h5 class="card-title">{contact.name}</h5>
</div>
</div>
))}
</div>
)
};
export default Contacts
The data does not get rendered or logged. Is there an issue in the way I'm fetching it?
EDIT: The issue is related to CORS. Not sure why using flask_cors doesn't resolve it. My server looks like:
from flask import Flask, request, json
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route("/")
def home():
return json_response([{"name":"Hello World!"}])
def json_response(payload, status=200):
return (json.dumps(payload), status, {'content-type': 'application/json'})