![](/img/trans.png)
[英]How to “mount” an Angular 2 module's routes at a certain point in the routing hierarchy
[英]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.
杂项信息
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.