简体   繁体   中英

× React - fetch('/') won't hit index route in Express.router

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!

With your front-end app being served from http://localhost:3000 and your back-end data api served from http://localhost:3001 , doing a fetch('/') will request data at http://localhost:3000 .

Having the 'proxy' param set in your front-end package.json will NOT change that. This param is used, for instance, for node apps running outgoing requests, not for a React app.

So to retrieve your back-end data from the front-end, you have to do a fetch('http://localhost:3001/') . If you want to avoid repetition, and to prepare for production, you could define your API base URI in a separate file, ie a config.js file located at the root of your client source tree:

// general config goes here
const configGlob = {};
// production specific config goes here
const configProd = {
  API_URI: "http://www.example.com/api/v2"
};
// development specific config goes here
const configDev = {
  API_URI: "http://localhost:3001"
};

// merged config
const config = { ...configGlob, process.env.NODE_ENV === 'production' ? ...configProd : ...configDev };
export default config;

And then in your App.js :

import config from './config';
...
fetch(`${config.API_URI}/`)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM