我正在開發一個使用 web pack 捆綁的 Express/React 應用程式。我的 index.js 檔案中有兩條路線。App.js 的路由是“/”。我在“聊天”有一條到 Chat.js 的路線。到 App 的路由有效,并在瀏覽器中顯示來自 / 的測驗標題。Chat 的路由在瀏覽器中給出錯誤 {"message":"Page not found for GET /chat"}。這是 index.js:

“react”:“^18.2.0”,“react-dom”:“^18.2.0”,“react-router-dom”:“^6.4.3”,
我嘗試將路線從 <Route path='/chat' 更改為 <Route path='chat'
我已經使用 react 2 年了,自從新版本的 react (18) 和 react-router-dom (6.4) 以來,我一直無法讓單個應用程式作業
我希望聊天頁面顯示在瀏覽器中,而是得到 {"message":"Page not found for GET /chat"}
uj5u.com熱心網友回復:
將此代碼用于您的 server.js 檔案:
const express = require('express');
const path = require('path');
const app = express();
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
app.use('/dist', express.static(path.join(__dirname, 'dist')));
// If no other routes are hit, send the React app
app.use((req, res) => res.sendFile(path.join(__dirname, '/index.html')));
app.use((req, res, next) => {
next({
status: 404,
message: `Page not found for ${req.method} ${req.url}`,
});
});
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
message: err.message || JSON.stringify(err),
});
});
app.listen(process.env.PORT, () => console.log('Listening on PORT ', process.env.PORT));
我已經使用您的存盤庫在本地運行它并且它有效。我還將作業更改推送到 GitHub ( https://github.com/rsg71/react-stack-overflow ) 中的示例存盤庫。
您需要更改的是在不指定 GET / 端點的情況下發送 React 應用程式:
以前你有:
app.get('/', (req, res, next) => {
try {
res.sendFile(path.join(__dirname, 'index.html'));
} catch (error) {
next(error);
}
});
你需要的是:
// If no other routes are hit, send the React app
app.use((req, res) => res.sendFile(path.join(__dirname, '/index.html')));
現在 react-router-dom 包可以處理路由。否則,你依賴 express 來路由你的 React 應用程式,這不是你想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529541.html
標籤:反应表示反应路由器dom
上一篇:用戶提供的容器無法啟動并監聽PORT=8080提供的埠
下一篇:Java腳本物件速記
