I have a rare issue fetching data on a useEffect hook....It gives me "CORS error" on chrome inspector... here is my code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './HomeScreen.css'
import config from '../config'
// Compomnents
import Quiz from "../components/Quiz";
const HomeScreen = () => {
const [data, setData] = useState({ quizzes: [] });
const [loading, setLoading] = useState('true');
const [error, setError] = useState(false);
console.log("TESTING...............................");
useEffect(() => {
setLoading('testing');
const url = "https://mocki.io/v1/4a0ad1a9-352a-45bb-84b9-67e6363d6b7a"; //config.prodLocalhostURLRestAPI + 'quizzes';
fetch(url)
.then(res => res.json())
.then(res => {
setLoading('result..........')
})
.catch(error => {
//console.log(error);
});
}, []);
return (
<div className="homescreen">
<h2 className="homescreen__title">Quizzes</h2>
<div className="homescreen__quizzes">
<h2>{loading}</h2>
{loading ? <h2>Loading............</h2> : error ? <h2>ERROR</h2> : data.quizzes.map(quiz => (
<Quiz />
))}
</div>
</div>
)
}
export default HomeScreen;
The server code is:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require("mongoose");
const port = process.env.OPENSHIFT_NODEJS_PORT || 3011;
app.set('port', port);
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.use(bodyParser.json());
app.use(methodOverride());
//Import routes
const chatsRoutes = require('./routes/quizzes');
app.use('/quizzes/', chatsRoutes);
app.get('/', (req, res) => {
res.send("Ready!");
});
/** catch 404 and forward to error handler */
app.use('*', (req, res) => {
return res.status(404).json({
success: false,
message: 'API endpoint doesnt exist'
})
});
//app.use('/', routesRaids);
mongoose.connect('mongodb://localhost/quizes', {useNewUrlParser: true, useUnifiedTopology: true }, () =>
console.log('Connected to Mongo DB')
);
app.listen(port);
The URL is correct and works directly on the browser.
What's the issue?