I'm doing some tests with React and Express. The final goal is to get Express to connect to a Mysql database and get data from it.
I understand how both React and Express work fairly well, and after a few tries I've been able to get my React app to get data from Express. This was done by running React on port 3000 and my server.js on port 8080 by following this guide.
What confuses me now that I've got this to work locally, is how am I supposed to get it to work after building my app.
I built it and uploaded it to check if it worked, but of course it didn't.
If you check the console you'll see it's not able to contact /ping.
Does express only work locally? I'm having a hard time figuring this out.
Here's my scripts just in case:
App.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
componentDidMount() {
fetch('/ping')
.then(response => response.json())
.then(posts => console.log(posts))
}
render() {
console.log(process.env.PORT)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
server.js:
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/ping', function (req, res) {
return res.send(JSON.stringify({ a: 1 }));
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
Edit: I wrote the wrong title, fixed it now.