【问题标题】:Express server serves up react build files without needing app.get('/')Express 服务器无需 app.get('/') 即可提供反应构建文件
【发布时间】:2021-01-24 04:46:11
【问题描述】:

所以我的 node.js express 服务器与我的 react 前端配合得很好,但我很困惑为什么它可以工作......

这是我的 server.js 文件

var express = require('express');
var app = express();

var path = require('path');

var server = require('http').Server(app);
var io = require('socket.io')(server);


// Set up the path for the quickstart.
var quickstartPath = path.join(__dirname, './quickstart/public');
app.use('/quickstart', express.static(quickstartPath));


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


server.listen(process.env.PORT || 4000);
console.log('server running');


//WHY IS THE App.get(/) NOT NECESSARY?!
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


我对我的 react 文件进行了 npm run build,然后将该构建文件夹/目录移动到与我的 server.js 文件相同的目录中。

我节点 server.js 并通过转到 localhost:4000,整个事情运行良好!

但如果我删除app.get('/'),它仍然可以正常工作。

只有当我删除 app.use(express.static(path.join(__dirname, 'build'))) 时,才会加载 index.html(位于 ./build/index.html)。

我认为通过输入 localhost:4000 会向 \ 发出 get 请求并从那里发送 index.html 文件,但 app.get 没有被调用?

我只是想了解原因,尽管一切都很好。

谢谢!

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    这是因为express.static()默认发送指定目录的索引文件,在你的情况下,它是build/index.html

    在此处查看文档,

    https://expressjs.com/en/4x/api.html#express.static

    express.static(root, [options])
    

    您可以通过将选项的index 属性设置为false 来禁用它

    app.use(express.static(path.join(__dirname, 'build'), { index: false }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2020-01-25
      • 2022-07-16
      • 1970-01-01
      • 2013-11-09
      • 2021-09-07
      • 2017-03-31
      相关资源
      最近更新 更多