首页 > 解决方案 > 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

标签: node.jsreactjswebpackreact-router

解决方案


创建一个文件夹 build 并将构建文件复制到此文件夹中

将构建文件夹设置为静态

app.use(express.static(path.join(__dirname, 'build')));

然后

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

推荐阅读