簡體   English   中英

在 Express 服務器上使用 react-router

[英]Using react-router with Express server

我有一個由簡單的 Express 服務器提供服務的 React 應用程序。 React 應用程序正在被webpack到我的根目錄( server.js文件也位於該目錄)中一個名為dist目錄中。 dist 文件夾包括index.html入口點、 main.min.js JavaScript 包和所有其他靜態資產(css、圖像等)。

如果我訪問站點的根目錄,例如localhost:3000/index.html得到服務,它加載 JS 包並找到所有其他資產。 該應用程序使用react-router ,通過單擊按鈕和將我帶到localhost:3000/feature的鏈接正常導航。

但是,如果我手動去到地址欄並鍵入localhost:3000/feature ,服務器對的index.html預期,同時也提供index.html代替main.min.js 這是因為 express 服務器中的通配符路由被映射到返回index.html 這是我在一些文章中看到的方式,但我不確定是否考慮過這種情況。

這是相關服務器代碼的片段:

app.use(express.static(path.join(__dirname)));
app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

這就是定義服務器路由的內容。 有沒有更好的方法可以允許手動更改地址?

如果有幫助,這是我的文件結構:

|-root
  |-server.js
  |-webpack.config.js
  |-dist/
    |-main.min.js
    |-index.html
    |-a2cea76fae187add3c974dcacf446eab.jpg
    |-...etc

index.html內容:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <div id="root"><!-- React app --></div>
    <script src="dist/main-631cea2c7e308b1dfb26.min.js"></script>
</body>
</html>

這是因為您正在使用相對路徑引用您的腳本。

例如,當在http://localhost:3000/feature ,瀏覽器會將腳本解析為http://localhost:3000/feature/dist/main-631cea2c7e308b1dfb26.min.js這當然不存在,因此express.static中間件讓請求落入下一個中間件。

因此,您需要將其定義為根相對路徑,例如

<script src="/dist/main-631cea2c7e308b1dfb26.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM