【问题标题】:how to use serve static file with express and react?如何使用快速服务静态文件并做出反应?
【发布时间】:2020-08-06 01:03:36
【问题描述】:

我有一个使用 create-react-app 制作的项目,我想在 express 中使用它(因为我需要一些后端功能)。

基本上,我的服务器在我运行它时会呈现一个空白页面...... 这是我的服务器的代码:

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

const app = express();

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'public')));

// An api endpoint that returns a short list of items
app.get('/api/getList', (req,res) => {
    var list = ["item1", "item2", "item3"];
    res.json(list);
    console.log('Sent list of items');
});

// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
    res.sendFile(path.join(__dirname , 'public', 'index.html'));
});


const port = process.env.PORT || 5000;
app.listen(port);

console.log('App is listening on port ' + port);

如果我输入端点http://localhost:5000/api/getList,我可以看到结果,但是当我想为另一个端点显示我的反应应用程序时,页面是空白的。

react 应用使用不同的路由,我还在 package.json 中添加了一个代理。

我的服务器源文件与图像一样位于 react 应用程序的根目录。

有人知道为什么 react 应用程序不显示吗?

谢谢

【问题讨论】:

  • 您是否构建了您的 React 应用程序? cra 的输出将创建一个 build 文件夹
  • 公用文件夹不会将您的反应应用程序作为静态资产包含。它是在开发过程中使用的,当你构建时,它的内容会被复制到构建文件夹中
  • 不,我还没有构建。让我尝试构建它并将“公共”更改为“构建”
  • @azium 感谢构建后,它的工作原理。感谢您对公用文件夹的解释

标签: javascript node.js reactjs express create-react-app


【解决方案1】:

你有两行在做同样的事情:

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'public')));

会将您的 index.html 文件提供给http://localhost:5000/index.html

根据 Express 文档https://expressjs.com/en/starter/static-files.html

然后好像你有第二条路线:

app.get('*',格式不正确。

必须是app.get('/*'

如果您不将用户引导至多条路线,那么最好只使用根目录 app.get('/', 而不是尝试捕获所有路线。

【讨论】:

  • 嗨,如果我只使用 app.get('/') 我不能去另一条路线,这就是我使用 app.get('*') 的原因
猜你喜欢
  • 1970-01-01
  • 2018-04-29
  • 2018-05-14
  • 1970-01-01
  • 2014-11-17
  • 2013-04-26
  • 2019-04-04
  • 2020-03-15
  • 2020-08-21
相关资源
最近更新 更多