node.js - 无法使用 Express / Node 提供静态 HTML 文件
问题描述
我正在使用 Express 和 Node,然后用它构建一个 React 应用程序,它是单页的,除了一个静态 HTML 文件。
我有这个在本地工作,所以当我去的时候localhost:3000/static-file.html
,我可以看到文件。但这在生产中不起作用。
我什至无法点击任何测试console.log
语句,所以我知道在请求static-file.html
. app.js
请参阅我文件的以下部分:
if (process.env.NODE_ENV === "production") {
app.get('/static-file.html', function (req, res) {
console.log('test1');
});
app.get('static-file.html', function (req, res) {
console.log('test2');
});
app.get('static-file', function (req, res) {
console.log('test3');
});
app.get('/static-file', function (req, res) {
console.log('test4');
});
app.use(express.static("client/build"));
}
当我转到 production-site.com/static-file.html 时 - 我仍然看到索引,与 localhost 不同。
有人可以帮我吗?非常感谢。
解决方案
Try something like this:
const express = require('express');
const app = express();
const path = require('path');
// the __dirname is the current directory from where the script is running
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/build/index.html'))
})
/* Here build is the production build directory and index.html is the main html page to show */
推荐阅读
- assembly - 执行此代码段后存储在 eax 中的十六进制值是多少?
- javascript - SVG 在使用 svg4everybody 但在 Firefox 和 Chrome 中工作时无法在 IE11 中呈现
- dart - Flutter 编辑列表项
- python - 在 if 状态下更改等效值
- c# - Unity DI 替换 Container.Resolve 正确
- javascript - 导入模块时无法解析 React
- angular - 路由在角度 6 中无法正常工作
- java - 使用 ARM64 musl-libs 编译 OpenJDK 9 及更高版本
- javascript - 在angularjs中的行和列中创建动态复选框按钮
- angular - Angular 6 创建动态组件