【发布时间】:2019-12-18 21:56:56
【问题描述】:
我有一个由 express 提供的 react 应用程序。整个应用程序包含在 public/index.html 中。
现在我的 server.js 看起来像这样:
1 const express = require('express');
2 const path = require('path');
3 const port = process.env.PORT || 8080;
4 const app = express();
5
6 // the __dirname is the current directory from where the script is running
7 app.use(express.static(__dirname));
8
9 app.get('*', (req, res) => {
10 res.sendFile(path.resolve(__dirname, 'public/index.html'));
11 });
12
13 app.listen(port);
但是,不知何故,正在提供诸如 package.json 和 /.ssh/known_hosts 之类的文件,这些东西显然不应该可用。
我不确定为什么 app.get('*', (req, res)... 没有捕获所有请求,以及为什么 app.use(express.static(__dirname)); 似乎是允许我的应用服务器任何静态文件的唯一配置。
app.use(express.static(__dirname+'/public')); 或
app.use( '/', express.static(__dirname + '/public'));
或任何我能找到的东西。
编辑---
我的项目目录如下:
/myproject
package.json
server.js
/public
index.html
我希望所有请求都只为 index.html 提供服务
我还是不明白为什么
app.use('*', express.static(path.resolve(__dirname,'/public/index.html')));
不提供任何服务。
另外,为什么在上面的例子中, res.sendFile() 没有先调用 express.static() 什么都不做。如果我删除第 7 行,则不会提供任何内容。
【问题讨论】:
标签: node.js reactjs express single-page-application