I am brand new to react/dev generally so am probably being an idiot. I have a local mySQL database that I am trying to pull data from to my front end react app using an express server.
I have set up the server as:
// This is the routes.js file!
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'asdf'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'xxxx' table.
app.get('/xxxx', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'xxxx' table).
connection.query('SELECT * FROM xxxx', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(process.env.PORT || 8080);
Added a proxy to the package.json file:
.....
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"proxy": "http://localhost:8080",
"scripts": {
"start": "react-scripts start",
......
and have called it in my app.js
componentDidMount() {
fetch('http://localhost:8080/xxxx')
.then(response => response.json())
.then(xxxx=> this.setState({ xxxx }, () => console.log("successfully fetched xxxx", xxxx)));
}
however am still getting the following error:
Access to fetch at 'http://localhost:8080/xxxx' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Should the proxy not prevent this? What am I doing wrong (I can see all of the data at localhost:8080/xxxx)