Javascript 修复生产的react路由时,fetch找不到api url

Javascript 修复生产的react路由时,fetch找不到api url,javascript,reactjs,express,react-router,fetch,Javascript,Reactjs,Express,React Router,Fetch,我有一个反应前端和一个快速后端。express只是在生产中从react端提供静态构建文件。我在生产中遇到了一个问题,许多人都遇到过,因此我将其修复为: server.js: app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'client', 'build', 'index.html')); }); app.get('/api/customers', (req, res) => { cons

我有一个反应前端和一个快速后端。express只是在生产中从react端提供静态构建文件。我在生产中遇到了一个问题,许多人都遇到过,因此我将其修复为:

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);
});
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
“/*”解决了生产中的路由问题,但现在“/api/customers”的获取不再有效

customer.js:

  componentDidMount() {
    fetch('/api/customers')
      .then(res => res.json())
      .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)))
      .catch(() => console.log('Error'));
  }
此提取请求在运行时记录“错误”。似乎由于server.js中的“/*”更改,api的url正在以某种方式发生更改,但我不确定应该如何更改fetch参数以使其正常工作。正在使用“/”进行提取:

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);
});
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

然而,这显然阻止了react路由在生产中的工作。我需要将fetch参数更改为什么才能执行此操作?

server.js
中更改路由顺序:

app.get('/api/customers', () => {});
app.get('/*', () => {});

express中的路由是,当“/api/customers”匹配“/*”时,如果您以相反的方式列出它们,它将返回index.html。

非常感谢您提供此解决方案@David Filipidisz!!顺序确实会影响路线。这是我的工作代码

server.js

…在这里

app.use('/users', require('./users/users.controller'));
app.use('/machineLearning', require('./machineLearning/machineLearning.controller'));
app.use('/public', require('./public/public.controller'));

//for Prod
app.use(express.static(path.join(__dirname,'../L10-ui/dist')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '../L10-ui/dist', 'index.html'));
});```

这和我不明白有什么关系?