Node.js React应用程序在主js和css上提供404
我使用“react脚本”构建了一个react应用程序。该应用程序在我的本地开发服务器上运行良好,但当我部署到实际服务器时,应用程序似乎找不到正在编译的主要JS和CSS文件。两个都是404 以下是可能有帮助的信息。 服务器上的文件位于 分别为ads/build/static/js和ads/build/static/css | | 我得到的404在以下文件中: 以下是我的服务器的配置方式:Node.js React应用程序在主js和css上提供404,node.js,reactjs,express,routing,react-scripts,Node.js,Reactjs,Express,Routing,React Scripts,我使用“react脚本”构建了一个react应用程序。该应用程序在我的本地开发服务器上运行良好,但当我部署到实际服务器时,应用程序似乎找不到正在编译的主要JS和CSS文件。两个都是404 以下是可能有帮助的信息。 服务器上的文件位于 分别为ads/build/static/js和ads/build/static/css | | 我得到的404在以下文件中: 以下是我的服务器的配置方式: const express = require('express'); const path = requ
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);
在my package.json中,我还将主页参数包括为:
“主页”:https://www.example.com/ads
更新
当我使用以下路径在服务器上运行应用程序时:
专用服务器主机:9000/static/js/main.74995495.js
正确呈现js文件
是否有我缺少的一些配置,路由似乎不起作用。请建议。使用一些缩进,这样您将看到如下错误:
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.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更改为使用:
有时,首先正确设置路径结构可以使路由处理程序更容易。也许在HTML中添加
标记会有所帮助?尝试将应用程序。使用(express.static…
移动到路由之外handler@YouneL听起来是个好主意,让我试试that@YouneL这似乎对app.use没有帮助('/ads/build/static',express.static(path.join(u dirname,'build/static'));工作正常!
app.use('/ads', express.static(path.join(__dirname, 'build')));