我有一个 React 应用程序正在构建到我的项目的/dist 目录中,我正在尝试通过我的 Express 服务器提供 bundle 和所需的文件,以及连接到 mongo 并为那里的一些数据提供 api。
现在我无法加载我的应用程序。我在 localhost:5000 处收到错误GET http://localhost:5000/dist/bundle.js net::ERR_ABORTED 404 (Not Found)
下面是我的服务器文件,项目的其余部分是 here
服务器.js:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
const app = express();
const port = process.env.PORT || 5000;
//connect to the database
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));
// overide mongoose promise (depricated) with node's promise
mongoose.Promise = global.Promise;
app.use((req, res, next) => {
// TODO: should header be set on res or req?
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use('/api', routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/../index.html'));
});
app.use('/../dist', express.static('dist'));
app.listen(port, () => {
console.log(`Server running on port ${port}`)
});
最佳答案
开始工作了。尽管我建议切换到我的 fullstack-mern-kit ,但这由您决定。
无论如何,请按照以下步骤操作...
在 package.json
更改scripts
至:
"scripts": {
"dev": "webpack-dev-server --config ./webpack.config.js --mode development",
"build": "webpack --mode=production",
"start": "node ./server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
在您的 dist
中文件夹中,添加 index.html
(您还需要在编译的 <link>
样式表中包含 css
):
<!DOCTYPE html>
<html>
<head>
<title>The Minimal React Webpack Babel Setup</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>
在您的 server.js
中文件,像这样修改它:
const express = require("express");
const app = express();
const { resolve } = require("path");
app.get("/sampleData", (req, res) => {
res.send("sample data");
});
app.use(express.static("dist"));
app.get("*", (req, res) => res.sendFile(resolve("dist", "index.html")));
app.listen(8080);
运行npm run build
,然后npm start
,然后导航至 http://localhost:8080
。
关于javascript - 我正在尝试通过 Express 为我的 React 应用程序提供服务,为什么会收到 404 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252336/