对 JS 和 CSS 的请求改为提供 index.html

IT技术 javascript reactjs express create-react-app
2021-05-12 14:52:12

我正在使用Expresscreate-react-app

我的 React 应用程序是一种方式,现在我正在尝试从 Express 服务器提供它。

// server/app.js

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

const app = express();

// Serve static assets

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

// serve main file

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});


module.exports = app;

(当我执行npm run build.

我在 Chrome 中查看页面,加载页面时发生的事情localhost:3000是 Console prints Uncaught SyntaxError: Unexpected Token <,并且在 Sources 选项卡中,它显示我的 CSS 和 JS 文件的内容与index.html:相同,如图所示。

HTML 覆盖了我的 JS 和 CSS?

这似乎是一个公认的问题,所以希望有人以前见过这个。我什至不知道从哪里开始,特别是因为我实际上是从 Express 成功地为应用程序提供服务的。然后这开始发生,然后它在 git 分支的一些随机切换并恢复和重播更改后停止,然后它再次开始发生。所以我什至不确定是什么让它发生或不发生。

3个回答

看来您的app.use(express.static...调用失败了,因此所有请求(包括静态资产)都由该app.get('*', (req, res) => {部件处理

当您打算使用它来为 React 应用程序提供服务时,我建议从样板中汲取灵感,“看看它是如何完成的”。我个人使用 NYTimes 的 kyt 项目,也有 react-starter-kit。

尝试从express 文档中详细介绍以下代码更改- 在 express 中提供静态文件

代替

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

app.use(express.static('build'))

消除

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});

问题出"homepage": ...package.json.

npm run build运行时 package.json 中有一个主页 URL 有一个非空路径(像这样的 Github Pages URL,https://username.github.io/project_name,其中“/project_name”是路径),它改变了它期望里面的文件所在的位置/build对我的 js 和 css 的请求将改为/project_name/static/...而不是/static/....

它甚至在日志输出中说npm run build

The project was built assuming it is hosted at /project_name/.
You can control this with the homepage field in your package.json.

在我的本地主机上,它不在 托管/project_name/,因此路径已关闭。