简体   繁体   English

我正在尝试通过 express 为我的 React 应用程序提供服务,为什么我会收到 404?

[英]I'm trying to serve my react app from express, why am I getting a 404?

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.我在项目的 /dist 目录中构建了一个 React 应用程序,我正在尝试通过我的快速服务器提供捆绑包和所需文件,并连接到 mongo 并为那里的一些数据提供 api。

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我在 localhost:5000 收到错误GET http://localhost:5000/dist/bundle.js.net::ERR_ABORTED 404 (Not Found)

Below is my server file and the rest of the project is here下面是我的服务器文件,项目的rest在这里

server.js:服务器.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. 尽管我建议切换到我的fullstack-mern-kit ,但这由您决定。

Anyway, follow these steps... 无论如何,请按照以下步骤操作...

In the package.json change scripts to: package.jsonscripts更改为:

  "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): 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>

In your server.js file, rework it like so: 在您的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);

Run npm run build , then npm start , then navigate to http://localhost:8080 . 运行npm run build ,然后npm start ,然后导航到http://localhost:8080

You may need to build the app first.您可能需要先构建应用程序。 Use this command and then try serving: npm run build使用此命令,然后尝试服务: npm run build

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在与节点反应时对此得到404 - Why am I getting a 404 on this in react with node 为什么我的 Express 服务器收到“404 cannot POST”错误? - Why am I receiving "404 cannot POST" error from my Express server? 为什么我会收到 404? - Why am I getting a 404? 为什么我在node.js应用程序中获得404状态? - Why am I getting a 404 status in my node.js app? 为什么我的 Javascript 收到 404 错误消息? - Why am I getting a 404 error message in my Javascript? 当我试图启动我的反应应用程序时,我收到一个不寻常的错误。 它说CleanWebpackPlugin不是构造函数 - I'm getting an unusual error when I'm trying to start my react app. It says that CleanWebpackPlugin is not a constructor 我收到错误消息:```TypeError: Object(...) is not a function``` in my react app- 第一次尝试使用钩子 - I'm getting the error: ```TypeError: Object(…) is not a function``` in my react app- trying to use hooks for the first time 为什么我在 express 中收到 404 错误?我已在视图和路由文件夹中正确创建了文件 - Why am i getting the 404 error in express?I have created the files correctly in views and routes folders 为什么我的本地node.js / express服务器的响应中没有得到JSON对象? - Why am I not getting a JSON object in the response from my local node.js/express server? 我正在尝试从Openweather API获得响应,但是却收到404 - I am trying to get response from the Openweather API but I am getting a 404
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM