我有以下服务器代码:
var express = require('express');
var webpack = require('webpack');
var app = express();
//app.use(express.static(path.join(__dirname, "public")));
app.use("/", express.static(__dirname + "/public"));
//both not working. I have tried multiple ways....
app.get("/",function (req, res){
res.sendFile(__dirname + "/public/index/index.html")
});
app.listen(3000);
Webpack配置
module.exports = {
entry: './app/index/index.js',
output: {
path: path.resolve(__dirname, 'public/index'),
publicPath: '/public/index',
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index/index.html'
})
]};
以下目录结构:
-public
-index
-index_bundle.js
当我尝试加载index_bundle js时出现以下错误:
获取http://localhost:3000/public/index/index_bundle.js 404(未找到)
我无法修复它,我在网上找不到任何解决方案。
答案 0 :(得分:6)
更改
app.use("/", express.static(__dirname + "/public"));
到
app.use("/", express.static(__dirname));
您可以使用DEBUG=* node <your-server-file>.js
调试此类明确的相关问题。
更安全的解决方案:
var path = require('path');
var express = require('express');
var app = express();
app.use("/public", express.static(path.resolve(__dirname, 'public')));
app.get("/",function (req, res) {
res.sendFile(__dirname + "/public/index/index.html")
});
app.listen(3000);