简体   繁体   中英

Cannot GET / with webpack-dev-server

How come I am getting Cannot GET / in my browser? I think it is because my webpack-dev-server does not have a route to GET the bundled files.

devServer/server.js

import config from '../../webpack.config';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import open from 'open';

// template! https://github.com/webpack/webpack-dev-server/blob/master/examples/node-api-simple/server.js

const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
  contentBase: '../dist/',
  stats: {
    colors: true
  }
});

server.listen(3000, '127.0.0.1' ,err => {
  if (err) {
    console.log(err);
  } else {
    console.log('Dev Server listening on port 3000!\n');
    open("http://localhost:3000");
  }
});

webpack.config.js

import webpack from "webpack";

export default {
  entry: [
    "./app/index"
  ],
  devtool: "inline-source-map",
  output: {
    path: __dirname + "/app/dist/", // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: "/",
    filename: "bundle.js"
  },    
  plugins: [    
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
  module: {
    rules: [
      { test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
        loader: 'babel-loader',
        options: {
          presets: ['env', 'react']
        }
      }}
    ]
  }
};

Project structure

在此处输入图片说明

On successful build a folder dist will be created inside the app folder which currently is not there.

Once the folder is created you can try by directly hitting the file path

http://localhost:3000/app/dist/yourfile

You can access your page via localhost:3000

When you access this path webpack dev server is searching for an index.html file to serve (like any other webserver). It can not find an index.html file because you have no index.html file. The index.html file is served from the static directory, which you have defined via property contentBase: '../dist/', . but as I see you have no directory named dist and you have no index.html in this directory.

Your script is served from the public path, that is / in your config, so you have to reference this in your index.html

Solution:

Create directory dist and put an index.html file there with the following content:

<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
    </head>
    <body>
      <script src="/bundle.js"></script>
    </body>
  </html>

For more information read here: https://webpack.github.io/docs/webpack-dev-server.html

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