我有新的反应。我一直在尝试将我的MEAN堆栈应用程序转换为express和reactjs应用程序,但是我在构建文件正确进入时遇到了问题。看起来我的服务器正在加载我的index.html文件来代替我的js文件。任何人都可以帮我找出原因吗?
我在浏览器的main.js中遇到以下错误:Uncaught SyntaxError: Unexpected token <
我的文件内置在build文件夹中,该文件夹是我的server.js文件的兄弟。 mywebsite(root) -src(f) - 建造(f) -server.js -public(f)
这是我的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>
如果你看到我没看到的东西,请告诉我。我走了一圈。提前谢谢!
答案 0 :(得分: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'));
});
答案 1 :(得分:1)
这里发布的内容接近答案。谢谢大家的帮助!我真正的问题是我忘记了.htaccess文件。请参阅:https://github.com/facebook/create-react-app/issues/1171和https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#deployment