【问题标题】:Express Only Serving Static FilesExpress 仅提供静态文件
【发布时间】:2018-02-18 00:06:28
【问题描述】:

我正在使用 React 和 Express 构建一个应用程序,并希望路由主要通过 Express 而不是 react-router。

在我构建了 React 应用程序并将 Express 设置为从构建文件夹提供静态文件之后,每个路径都只指向 React 应用程序。例如访问 localhost:3000/test 时,我仍然只得到 React 应用而不是“测试”。

const express = require('express');
const path = require('path');
const app = express();

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

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

app.get('/test', function (req, res) {
   res.send("testing");
});

app.listen(3000);

【问题讨论】:

    标签: javascript reactjs express


    【解决方案1】:

    您很可能不想要这样的结果,因为您希望将服务器端路由暴露给客户端,并且处理 SPA 文件的路由作为应用程序内的最后一个路由。但是这段代码对你有用。

    const express = require('express');
    const path = require('path');
    const fs = require('fs')
    const app = express();
    
    app.use(express.static(path.join(__dirname, './client/build')));
    
    app.get('*', function (req, res) {
       const file = fs.createReadStream(path.join(__dirname, '/client/build', 'index.html'));
       return file.pipe(res);
    });
    
    app.get('/test', function (req, res) {
       res.send("testing");
    });
    
    app.listen(3000);
    

    我希望这会有所帮助,编码愉快!

    【讨论】: