繁体   English   中英

为生产修复反应路由时,fetch 找不到 api url

[英]When fixing react-routing for production, fetch cannot find api url

我有一个带有快速后端的反应前端。 快递只是在生产中从反应端提供静态构建文件。 正如许多人遇到的那样,我在生产中使用 React 路由时遇到问题,所以我修复了它:

服务器.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);
});

'/*' 解决了生产中的路由问题,但现在 '/api/customers' 的获取不再有效。

客户.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 参数以使其工作。 提取仅使用“/”工作:

服务器.js:

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

但是,这显然会阻止反应路由在生产中工作。 我需要将 fetch 参数更改为什么才能使其正常工作?

更改server.js中路由的顺序:

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

express 中的路由先到先得,并且由于“/api/customers”匹配“/*”,如果您以相反的方式列出它们,它将返回您的 index.html。

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

服务器.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'));
});```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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