Express.js应用程序未提供静态资产

时间:2018-01-10 00:31:32

标签: javascript node.js express

不确定我为什么继续这样做: localhost GET http://localhost:3000/public/bundle.js 404(未找到) 我试图更改webpack.config文件的输出,我的服务器中的路由以及我的index.html捆绑文件位置。似乎没有什么能改变我一直得到的错误。有人可以帮忙吗?

Index.js



const express = require('express');
const bodyparser = require('body-parser');
const path = require('path');

const expressMiddleware = (app) => {
	app.use(bodyparser.urlencoded({ extended: false }));
	app.use(bodyparser.json());
	app.use(express.static(path.join(__dirname, '../../frontend/public')));
}

module.exports = expressMiddleware;




Webpack.config.js



const webpack = require('webpack');
const path = require('path');

module.exports = {
  entry: "./frontend/app.jsx",
  output: {
    path: path.join(__dirname,'/frontend/public'),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: [/\.jsx?$/, /\.js?$/],
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', `react`]
        }
      },
       {
        test: /\.css$/,
        loader: 'style!css!'
      },
      {
        test: /\.(ico|jpg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file'
      }
    ]
  },
  devtool: 'source-maps',
  resolve: {
    extensions: [".js", ".jsx", ".css"]
  }
};




的index.html



<!DOCTYPE html>
<html>
	<head>
	    <meta charset="utf-8">
	</head>

	<body>
	    <div id="app"></div>
	    <script type="text/javascript" src='/public/bundle.js'></script>
	</body>
<html/>
&#13;
&#13;
&#13;

Server.js

&#13;
&#13;
//Express
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;

//Files
const expressMiddleware = require('./middleware/index.js');

//Middleware
expressMiddleware(app);

// Frontend Route
app.get('/', (req, res) => {
	res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

app.listen(port, () => console.log('Running on 3000'));

//Export App
module.exports = app;
&#13;
&#13;
&#13;

Middleware.js

&#13;
&#13;
const express = require('express');
const bodyparser = require('body-parser');
const path = require('path');

const expressMiddleware = (app) => {
	app.use(bodyparser.urlencoded({ extended: false }));
	app.use(bodyparser.json());
	app.use(express.static(path.join(__dirname, '../../frontend/public')));
}

module.exports = expressMiddleware;
&#13;
&#13;
&#13;

指南 enter image description here

1 个答案:

答案 0 :(得分:0)

您似乎已将Express App设置为从公共文件夹中提供静态文件。

因此,在bundle.js中导入前端Index.html文件时,您的src应设置为/bundle.js,不需要包含/public因为Express已经在该目录中提供资产。

希望有所帮助,我真的不明白为什么你的资产不应该加载......

更多信息:https://expressjs.com/en/starter/static-files.html