javascript - 使用 Node 14 使 Express Static 停止 "pending"?

标签 javascript node.js express

我半年前问过这个问题,但我仍然遇到同样的问题:Express Static network requests stuck on "pending"
Tl; dr:Node 14 + Webpack watch mode + Express Static 导致浏览器在我每次更改 JS 文件时挂起。这发生在多个浏览器中,重新启动服务器后,清除缓存后。
让浏览器停止挂起的两种方法是:

  • 关闭并重新打开标签
  • 转到主页 (http://localhost)

  • 这个问题在 Node 12 中不会发生。有没有办法让浏览器在 Node 14+ 中停止挂起?
    编辑:这是我的 Express 代码,正在处理 repro 的 repo:
    const app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(cookieParser());
    app.use(cors({
      origin: HOME_URL,
      optionsSuccessStatus: 200,
    }));
    app.disable('x-powered-by');
    
    app.use('/api', apiRoutes);
    app.use('/sse', sseRoute);
    
    if (process.env.SERVER !== 'production') {
      app.use('/', express.static(
        path.resolve('./build/web'),
        { dotfiles: 'allow' },
      ));
    
      app.get('*', async (req, res) => {
        const indexFile = await fs.promises.readFile(
          path.resolve('./build/web/index.html'),
        );
        res.send(indexFile.toString());
        res.end();
      });
    } else {
      app.all('*', (req, res, next) => {
        if (req.secure || !USE_SSL) {
          next();
        } else {
          res.redirect(`https://${req.hostname}${req.url}`);
        }
      });
    
      app.use('/', express.static(path.resolve('../web')));
    
      const indexFile = fs.readFileSync(path.resolve('../web/index.html')).toString();
      app.use('*', async (req, res) => {
        res.send(indexFile);
        res.end();
      });
    }
    

    最佳答案

    如果您将SPA作为静态内容提供服务,您是否可以尝试更改此部分:

    app.use('/', express.static(path.resolve('../web')));
    
      const indexFile = fs.readFileSync(path.resolve('../web/index.html')).toString();
      app.use('*', async (req, res) => {
        res.send(indexFile);
        res.end();
      });
    
    有了这个:
    const path = require('path');
    const rootPath = path.normalize(__dirname);
    
    // Serve Angular/React frontend files 
    app.use('/', express.static(rootPath + '/web', { redirect: false }));
    
    // Rewrite virtual urls to Angular/React app
    app.get('*', function (req, res, next) {
        res.sendFile(path.resolve(rootPath + '/web/index.html'));
    });
    

    关于javascript - 使用 Node 14 使 Express Static 停止 "pending"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66948307/

    相关文章:

    javascript - Node/ express : Error: Failed to lookup view "error" in views directory

    javascript - 如何使 .env 变量在 JS 类构造函数中工作?

    javascript - 移动Web开发如何有效利用资源?

    javascript - D3。如何对选定的节点和所有父节点进行操作

    node.js - OAuth 2.0 Flow 它是如何工作的 node-oauth2-server

    javascript - 使用具有递归函数的 promise

    javascript - 将 $ajax 转换为 fetch() 以进行 PUT 请求

    angularjs - Angular 不响应 ui-router 的任何路由 - 当我输入时 URL 就消失了

    javascript - JS 恢复默认/全局函数

    javascript - 在构造函数中传递参数时无法设置对象的属性