I have a react app being built to my project's /dist directory, I'm trying to serve the bundle and required files via my express server, as well as connect to mongo and provide an api for some data there.
Right now I'm unable to get my app to load. I am getting an error GET http://localhost:5000/dist/bundle.js.net::ERR_ABORTED 404 (Not Found)
at localhost:5000
Below is my server file and the rest of the project is 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}`)
});
Got it to work. Although I'd suggest switching over to my fullstack-mern-kit , but that's up for you to decide.
Anyway, follow these steps...
In the package.json
change scripts
to:
"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"
},
In your dist
folder, add an index.html
(you'll also need include a <link>
to your compiled css
stylesheet):
<!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>
In your server.js
file, rework it like so:
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);
Run npm run build
, then npm start
, then navigate to http://localhost:8080
.
You may need to build the app first. Use this command and then try serving: npm run build
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.