Express无法正确提供React构建的静态文件

5

我对React还不熟悉。我一直在尝试将我的MEAN堆栈应用程序转换为一个使用Express和Reactjs的应用程序,但是我在正确获取构建文件方面遇到了问题。看起来我的服务器正在加载我的index.html文件代替我的js文件。有人能帮我弄清楚原因吗?

在浏览器中,我的main.js出现了以下错误:Uncaught SyntaxError: Unexpected token <

我的文件已构建为一个build文件夹,该文件夹是与我的server.js文件同级的兄弟目录。 mywebsite(根目录) -src(文件夹) -build(文件夹) -server.js -public(文件夹)

这是我的server.js

require('./server/config/config');

// Get dependencies
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

const api = require('./server/routes/api');

const compression = require('compression')
const app = express();

app.use(compression());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url 
HTTP/:http-version" :status :res[content-length] :response-time ms'));

// Serve static assets
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', api);

app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send("User-agent: *\nDisallow: /");
});

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

const port = process.env.PORT || '3001';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`API running on 
localhost:${port}`));
module.exports = app;

这是生成的 index.html 文件。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-
    fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/brookeclonts/brookeclonts.com/manifest.json">
    <link rel="shortcut 
    icon" href="/brookeclonts/brookeclonts.com/favicon.ico">
    <title>React App
    </title>
</head>

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript" src="/brookeclonts/brookeclonts.com/static/js/main.9ffbadeb.js">
    </script>
</body>

</html>

如果你看到了我没有看到的东西,请告诉我。我正在打转。提前感谢!


展示 index.html 文件。 - Eric Guan
我已经添加了!如果你还需要什么,请告诉我。@EricGuan - Brooke Clonts
2个回答

1

1
您也可以将目录合并为:

// Serve static assets

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

// Always return the main index.html

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

哎呀,那个也不行。抱歉 :/ 它还是给我同样的错误。 - Brooke Clonts
请问您能否分享一下您遇到的错误信息。 - Ayush Mittal
这是错误信息:在浏览器加载应用程序时出现 Uncaught SyntaxError: Unexpected token < - Brooke Clonts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接