React App在主js和css

时间:2018-02-09 16:29:52

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

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

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

  

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

我得到的404s是以下文件:

  

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文件

是否有一些我缺少的配置,路由似乎无法正常工作。请指教。

1 个答案:

答案 0 :(得分:2)

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

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 /广告请求中添加新的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')));

如果您希望问题中的网址生效。

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

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

并将index.html更改为使用:

而不是:

有时,首先将路径结构设置为正确可以使您的路径处理程序更加轻松。