簡體   English   中英

Nodejs路由沒有指向Angular App的所有內部路由

[英]Nodejs routing does not point to all inner routes of Angular App

我正在 Angular 9 上構建前端應用程序。為了服務應用程序,我使用 NodeJs 服務器接受所有請求並將它們指向 Angular 生成的 Dist(構建)文件。

問題陳述

Node 服務器收到的所有路由都應該轉發到 Angular 應用程序文件。

我面臨的問題

當我嘗試使用來自節點服務器的一些內部路由時,它會返回 404 響應。 但是當我在開發模式下運行 Angular 時,該頁面有效。

例如, localhost:4200/innerPage (Angular Dev Server) 可以工作,但localhost:8000/innerPage (Node Server) 不能工作。

但是,當我訪問localhost:8000時,會呈現 Angular 頁面。 只有 Angular 的內部路由在服務器上不起作用。

NodeJS 代碼是

const app = express();


app.use("/", express.static(__dirname + "../../dist/TournamentsPlatform/"));

app.listen(8000, () => console.log("Server started on port 8000"));

我之前嘗試過的

app.get("/", function (req, res) { res.sendFile(path.join(__dirname + "/../dist/TournamentsPlatform/")); });

app.use("/*", express.static(__dirname + "../../dist/TournamentsPlatform/"));

app.use(express.static(__dirname + "../../dist/TournamentsPlatform/"));

錯誤 - 瀏覽器控制台顯示

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

雜項信息

  • 我對所有 Angular 路由使用延遲加載。 每個頁面都是一個新模塊
  • 當我在內部路由到它時,該頁面工作正常。 因此,當我 go 到localhost:8000/ (NodeJS 服務器)然后單擊指向內部路由的鏈接時,它工作正常。 而當時瀏覽器URL是localhost:8000/innerPage

從 app.js 中刪除這一行有效

app.use(express.static(__dirname + "../../dist/TournamentsPlatform/"));

試試這個:

// fulfill the array with extensions that are part of what an angular
// app must need during load like: .js, .png, .jpg, .woff, .json etc
const allowedExtensions = ['.js'];

app.get('*', (req, res, next) => {
  if (allowedExtensions.some(ext => req.url.includes(ext))) {
    // remove the forward slash at the end of the path 
    const url = req.url.replace(/\/$/,'');
    res.sendFile(path.join(__dirname, 'dist', 'TournamentsPlatform', url));
  } else {
    res.sendFile(path.join(__dirname, 'dist', 'TournamentsPlatform', 'index.html'));
  }
});

順便說一句,除非第一個請求在路徑中顯式地帶來index.html (例如http://localhost/index.html ),否則這將不起作用,因為快遞不會知道默認服務文件:

app.get('*', 
  express.static(path.join(__dirname, 'dist', 'TournamentsPlatform'));

暫無
暫無

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

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