首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修复生产的react-routing时,fetch找不到api url

修复生产的react-routing时,fetch找不到api url
EN

Stack Overflow用户
提问于 2018-03-18 22:42:13
回答 2查看 668关注 0票数 0

我有一个快速后端的react前端。express只提供生产环境中react端的静态构建文件。我在生产中遇到了React路由工作的问题,就像许多人所遇到的那样,所以我修复了它:

server.js:

代码语言:javascript
复制
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’的fetch不再工作。

customer.js:

代码语言:javascript
复制
  componentDidMount() {
    fetch('/api/customers')
      .then(res => res.json())
      .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)))
      .catch(() => console.log('Error'));
  }

此获取请求在运行时会记录“错误”。由于server.js中'/*‘的变化,应用程序接口的url似乎发生了某种程度的变化,但我不确定应该如何更改fetch参数才能使其工作。fetch仅使用‘/’即可工作:

server.js:

代码语言:javascript
复制
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

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

EN

回答 2

Stack Overflow用户

发布于 2018-03-19 00:13:53

更改server.js中路由的顺序

代码语言:javascript
复制
app.get('/api/customers', () => {});
app.get('/*', () => {});

express中的路由是first come first served,当"/api/customers“匹配"/*”时,如果你的列表与之相反,它将返回你的index.html。

票数 1
EN

Stack Overflow用户

发布于 2019-10-27 05:51:25

非常感谢你的这个解决方案@David Filipidisz!顺序确实会影响路由。这是我的工作代码

server.js

这里是...ipmorts。

代码语言:javascript
复制
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'));
});```
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49349153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档