我正在尝试通过Express服务我的react应用,为什么我会收到404?

时间:2019-03-20 01:34:59

标签: javascript node.js reactjs express webpack

我在我的项目的/ dist目录中构建了一个React应用,我正在尝试通过我的Express服务器提供捆绑包和所需文件,并连接到mongo并在其中提供一些数据的api。

目前,我无法加载我的应用。我在本地主机: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}`)
});

1 个答案:

答案 0 :(得分:1)

开始工作。尽管我建议切换到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