簡體   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