我已经分别使用 angular-cli
和 express
命令行设置了一个 angular 和 express 应用程序。我已经使用 ng build
构建了 angular 应用程序,当我想使用 express server 为它提供服务时,我在 google chrome 控制台中收到以下错误:
Uncaught SyntaxError: Unexpected token < runtime.js:1
Uncaught SyntaxError: Unexpected token < polyfills.js:1
Uncaught SyntaxError: Unexpected token < styles.js:1
Uncaught SyntaxError: Unexpected token < vendor.js:1
Uncaught SyntaxError: Unexpected token < main.js:1
这是我的 server.js 文件:
.
.
.
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', usersRouter);
app.use('/auth', authRouter);
// Catch all other routes and return the angular index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/dist/client/index.html'));
});
index.html 文件:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Client</title>
<base href="./">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
ng serve
没有问题,应用程序会顺利运行,而且当我用浏览器打开 index.html 时它也能正常工作,我认为它在某种程度上与快速服务器有关。
最佳答案
正如 Mateusz 所说 - 您的所有请求都返回 index.html 文件。如果您在 Chrome 中打开开发人员工具并在“网络”选项卡下查看每个文件的响应,您将看到每个文件的内容实际上是 index.html 文件。您需要做的是制作一个异常(exception)列表,以允许服务器返回那些 js 文件和其他文件类型(如图像)。
const allowed = [
'.js',
'.css',
'.png',
'.jpg'
];
// Catch all other routes and return the angular index file
app.get('*', (req, res) => {
if (allowed.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
res.sendFile(path.resolve(`client/dist/cient/${req.url}`));
} else {
res.sendFile(path.join(__dirname, 'client/dist/client/index.html'));
}
});
关于javascript - Angular - 意外的标记 <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028765/