繁体   English   中英

Express 仅提供静态文件

[英]Express Only Serving Static Files

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

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

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);

很可能您不想要这样的结果,因为您希望将服务器端路由暴露给客户端,并将处理 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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM