webpack 我正在尝试从express提供我的react应用程序,为什么我会收到404?

r3i60tvu  于 2022-11-24  发布在  Webpack
关注(0)|答案(2)|浏览(178)

我有一个react应用程序正在我的项目的/dist目录下构建,我试图通过我的express服务器提供捆绑包和所需的文件,以及连接到mongo并为那里的一些数据提供一个api。
现在我无法加载我的应用程序。我在localhost:5000收到错误GET http://localhost:5000/dist/bundle.js net::ERR_ABORTED 404 (Not Found)
下面是我的服务器文件,项目的其余部分是here
server.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}`)
});
gcxthw6b

gcxthw6b1#

让它工作。虽然我会建议切换到我的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(您还需要在编译的css样式表中包含一个<link>):

<!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 buildnpm starthttp://localhost:8080

4urapxun

4urapxun2#

您可能需要先建置应用程序。请使用此命令,然后尝试提供:npm run build

相关问题