【问题标题】:React App giving 404 on main js and cssReact App 在主 js 和 css 上给出 404
【发布时间】:2018-07-20 11:31:45
【问题描述】:

我使用“react-scripts”构建了一个反应应用程序。该应用程序在我的本地开发服务器上完美运行,但是当我部署到我的实际服务器时,应用程序似乎找不到正在编译的主要 JS 和 CSS 文件。我都得到404。

以下是可能有帮助的信息。 服务器上的文件位于

ads/build/static/js 和 ads/build/static/css ||分别

我得到的 404 在以下文件中:

https://www.example.com/ads/build/static/css/main.41938fe2.css https://www.example.com/ads/build/static/js/main.74995495.js

这是我的服务器的配置方式:

const express = require('express');
const path = require('path');
const app = express();
const favicon = require('serve-favicon');

//favicon
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.get('/ads', function (req, res) {
app.use(express.static(path.join(__dirname, 'build/static')));
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});

app.listen(9000);

在我的 package.json 中,我还包含了 homepage 参数: "homepage" : "https://www.example.com/ads

更新 当我使用以下路径在服务器本身上运行应用程序时: dedicated-server-host:9000/static/js/main.74995495.js 正确渲染 JS 文件

我是否缺少某些配置,路由似乎不起作用。请指教。

【问题讨论】:

  • 在 HTML 中添加<base> 标记可能会有所帮助?
  • 尝试将app.use(express.static...移到路由处理程序之外
  • @YouneL 听起来不错,让我试试
  • @YouneL 似乎没有帮助

标签: node.js reactjs express routing react-scripts


【解决方案1】:

使用一些缩进,这样你会看到如下错误:

app.get('/ads', function (req, res) {
  app.use(express.static(path.join(__dirname, 'build/static')));
  console.log(path.join(__dirname, 'build'));
  res.sendFile(path.join(__dirname, '/build/index.html'));
});

您正在 /ads 处理程序内设置静态路由,将在每个 GET /ads 请求上添加一个新的 express.static 路由处理程序。

这将在服务器启动时设置静态路由:

app.use(express.static(path.join(__dirname, 'build/static')));
app.get('/ads', function (req, res) {
  console.log(path.join(__dirname, 'build'));
  res.sendFile(path.join(__dirname, '/build/index.html'));
});

或:

app.get('/ads', function (req, res) {
  console.log(path.join(__dirname, 'build'));
  res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.use(express.static(path.join(__dirname, 'build/static')));

但请确保您选择正确的路径 - 例如您可能需要:

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

如果您希望问题中的 URL 起作用。

为了更简单,您可以只使用这个单一的处理程序让 express.static 同时处理 css/js 和 index.html:

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

并更改您的 index.html 以使用:

代替:

有时,一开始就设置正确的路径结构可以使您的路径处理程序更容易。

【讨论】:

  • app.use('/ads/build/static', express.static(path.join(__dirname, 'build/static')));工作!
猜你喜欢
  • 2015-03-23
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多