我是网络开发新手。我通过 Angular 框架构建了我的前端部分,它运行良好,我的导航没问题,我的图像和内容也很好,到引导程序等库的链接也是一样的。
但是... 我想在后面部分开始使用node.JS,但不幸的是,当我在构建服务器后使用node server.js 命令启动服务器时,页面是静态的。所有导航都不再起作用,我的图像不再加载,我不明白为什么。你可以帮帮我吗 ? (VS CODE 中没有错误)
更多信息:
我在 VS Code 中没有错误
我在每次启动服务器之前都会重建我的文件
我使用 Angular 16(我不知道它是否非常有用,但你有信息)
我的server.JS文件
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
const mongoose = require('mongoose');
// Configuration de la gestion des fichiers statiques
mongoose.connect('mongodb://localhost/your-db-name')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './dist/three-percent/browser/index.html'));
});
app.get('/', (req, res) => {
res.send('Hello World from Node.js server!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
我的 tsconfig.json 代码
{
"compileOnSave": false,
"compilerOptions": {
"target": "es6",
"module": "es2020",
"outDir": "./dist",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"files": [
"server.ts"
],
"include": [
"src/**/*.ts"
],
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
chrome 上的错误:
我多次尝试启动我的服务器,希望该应用程序能够正常运行,并且我可以继续执行其他步骤,例如创建登录系统、通过表单检索信息等。
看起来您的 Express 服务器为您的所有静态资产(如图像和 js 文件)提供了
index.html
。text/html
MIME 类型。
在您的服务器代码中,您似乎通过以下方式传递静态资产:
app.use(express.static(path.join(__dirname, 'public')));
我猜没有
public
目录,这就是为什么它没有找到任何用于快速静态的资产,然后转到您的 '*'
路线,该路线提供 index.html
。
根据您的
'*'
路线和Angular的默认构建工件结构,我认为正确的路径应该是:
app.use(express.static(path.join(__dirname, 'dist', 'three-percent', 'browser')));
如果你改变那条线,我希望它能正常工作。
也就是说,我认为没有任何理由应该通过自定义 Express 服务器交付静态 Angular 资源。对于本地开发,使用 ngserve 是更好的方法。
ng serve
Builds and serves your application, rebuilding on file changes.
在其他环境(如生产、测试等)中,静态文件应由 CDN 或高效的 Web 服务器(如 nginx)传送。