node.js - Express ENOENT:没有这样的文件或目录,stat '/index.html'
问题描述
我在调试这个问题时遇到了一些麻烦。我几乎有一个 Node.js,它为 React 应用程序提供服务,也充当 REST API。服务器默认在 8080 端口上运行。
import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';
// Create express server
const app = express();
// Add middleware
app.use(helmet());
app.use(morgan('combined'));
// Define API routes
app.get('/api/', home.get);
// Configure environment settings
if (ENVIRONMENT === 'development') {
// ...
} else {
// Configure Static Files (Production)
app.use(express.static("./"));
// Serve React Static Files (Production)
app.get('*', (req: Request, res: Response) => {
res.sendFile(path.resolve(__dirname, "/index.html"));
});
}
// Start server
app.listen(PORT, () => {
console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});
export default app;
module.exports = app;
基本上我去 localhost:8080 并且我的应用程序渲染得很好。但是,当我转到 localhost:8080/login 时,我从服务器收到以下响应:
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
以下是摩根日志:
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
为什么它会呈现我的应用程序localhost:8080
但没有localhost:8080/login
分布文件夹:
dist
img
app.bundle.js
index.html
server.bundle.js
解决方案
创建一个文件夹 build 并将构建文件复制到此文件夹中
将构建文件夹设置为静态
app.use(express.static(path.join(__dirname, 'build')));
然后
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
推荐阅读
- github-actions - 错误:过程已完成,错误代码 1 – 自托管运行器上的 GitHub 操作
- python - 将 matplotlib 图转换为 json 对象
- css - 如何在网格显示中为每一行添加支撑线
- visual-studio-code - 文本结束后将 VSCode 装饰器应用于空白空间
- java - Spring无法从POST映射单个值
- error-handling - 来自 mozilla 的 NativeJSON.parse 的 RhinoException 没有 lineNumbers
- node.js - 如何在 tcp 套接字侦听器中唯一标识套接字 id
- powershell - 以编程方式获取 SharePoint Online 系统页面 html 内容
- node.js - MongoDb 没有与 express 连接
- php - 避免对 MySQL 日期时间列进行不必要的时间戳转换