I have a react front-end with an express back end. The express just serves the static build files from the react side in production. I was having a problem with React routing working in production, as many have had, so I fixed it as so:
server.js:
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
app.get('/api/customers', (req, res) => {
const customers = [
{id: 2, firstName: 'Test', lastName: 'Case'},
{id: 3, firstName: 'Foo', lastName: 'Bar'},
];
res.json(customers);
});
The '/*' solve the routing problem in production, but now the fetch for the '/api/customers' does not work anymore.
customer.js:
componentDidMount() {
fetch('/api/customers')
.then(res => res.json())
.then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)))
.catch(() => console.log('Error'));
}
This fetch request logs 'Error' when ran. It seems as though the url for the api is changing somehow as a result of the '/*' change in server.js, but I am not sure how I should change the fetch argument to make it work. The fetch was working using just the '/':
server.js:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
However, this obviously stops react routing from working in production. What do I need to change my fetch argument to in order to make this work?