简体   繁体   中英

Express.static() not working

I have following server code:

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 configs

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'
    })
]};

Following directory structure:

      -public
        -index
          -index_bundle.js

I get the following error when I try to load my index_bundle js:

GET http://localhost:3000/public/index/index_bundle.js 404 (Not Found)

I can't fix it and I found no solution on the web.

Change

app.use("/", express.static(__dirname + "/public"));

to

app.use("/", express.static(__dirname));

You can use DEBUG=* node <your-server-file>.js to debug such express related issues.

A better more secure solution:

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM