I've worked a bit with Express but am new-ish to React. I have React already hooked up to an Express server that works but having a problem getting fetch('/')
in my main React App component to hit the index route in my Express app. For example I have these route in Express:
app.use('/', routes);
app.use('/users', users);
Both routes are identical in Express. They make a simple call to MongoDB and the response is res.json(data)
. Also when I test these routes pure on the Express port they both work fine.
Below is my React component. The problem is when I try to use fetch('/')
to hit the corresponding app.use('/', routes);
in Express it doesn't work. If I change it to fetch('/users')
it works.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {users: []}
componentDidMount() {
fetch('/') // this route doesn't work with Express!
.then(res => res.json())
.then(users => this.setState({ users }));
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.users.map(user =>
<div key={user.id}>{user.username}</div>
)}
</div>
);
}
}
export default App;
Of course I could change the index route name to ('/index')
or something but I'd like to keep it as ('/')
route in the Express app if at all possible.
If anyone can point out what I am doing wrong or things I can try I'd be grateful. Thanks in advance!