7

我目前正在建立一个使用 webpack-dev-server 和骨干路由器的站点。

直到今天,一切似乎都在工作(例如,我可以转到http://localhost:3333我的主页和http://localhost:3333/login登录页面。

但是今天我尝试访问我的第一个嵌套 url,http://localhost:3333/people/1我的控制台抛出 404 GET 错误。

确切的错误是这样的: http://localhost:3333/people/build/bundle.js 404 (Not Found)

看来我的 webpack 服务器正在尝试在错误的目录下寻找正确的文件来服务器。如果这是正确的,我不知道如何解决这个问题。我查看了其他堆栈溢出问题和 github 问题,但无济于事。有什么想法吗?

我使用 gulp 启动服务器。这是我的 gulpfile:

var gulp = require("gulp");
var webpack = require("webpack");
var server = require("webpack-dev-server");
var config = require("./webpack.config");

gulp.task("serve", function() {
  new server(webpack(config), {
    publicPath: config.output.publicPath,
    historyApiFallback: true,
    hot: true,
    quiet: false,
    stats: { colors: true, progress: true },
  }).listen(3333, "localhost", function (err, result) {
    if (err) {
      console.log(err);
    } else {
      console.log("Listening at localhost:3333!");
    }
  });
});

gulp.task("default", ["serve"]);

这是我的 webpack 配置文件:

var webpack = require("webpack");

module.exports = {
  entry: [
    __dirname + "/app/app.js",
    "webpack/hot/dev-server",
    "webpack-dev-server/client?http://localhost:3333/",
  ],
  output: {
    path: __dirname + "/build",
    filename: "bundle.js",
    publicPath: "http://localhost:3333/",
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      { test: /\.jsx$/, exclude: /node_modules/, loader: "react-hot-loader!babel-loader" },
      { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
      { test: /\.scss$/, exclude: /node_modules/, loader: "style!css!sass" },
    ]
  },
  resolve: {
    root: __dirname,
    extensions: ["", ".js", ".jsx"],
  },
}

编辑:我刚刚发现我可以直接点击网址http://localhost:3333/#/people/1,或者http://localhost:3333/#people/1一切都按预期工作。

有没有一种设置可以让我不必在 url 中包含英镑符号?希望这有助于为我的问题提供更多背景信息。

跟进:我有一个全局App组件,用于初始化骨干路由器并调用Backbone.history.start({ pushState: true }). 这是一个代码片段。

class App {

  constructor() {
    console.log("starting up");
    this.Router = new Router();
    Backbone.history.start({ pushState: true });
  }
}

module.exports = new App();

如果您注意到console.log构造函数中的 ,这将在可以呈现的非嵌套页面上调用,但不会在不能呈现的嵌套页面上调用。

4

2 回答 2

11

我终于找到了我的问题的答案。

我在每个页面上加载的 index.html 文件曾经看起来像这样:

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>
    <script type="text/javascript" src="./build/bundle.js" charset="utf-8"></script>
  </body>
</html>

因为脚本的来源是相对路径,所以在嵌套的 url 上找不到脚本。

将源更改为此修复它:

<script type="text/javascript" src="http://localhost:3333/build/bundle.js" charset="utf-8"></script>

于 2015-05-04T05:57:18.213 回答
1

我知道这个问题已经得到解答,但我遇到了完全相同的问题,我想我会分享我的情况。就像 Warren 选择的解决方案一样,这个错误在我的 index.html 上。它最初看起来像这样:

<script src="./bundle.js"></script>

我看到了此处列出的解决方案以放入完整路径,但这对我不起作用,因为我想在本地和生产中运行它。我只是将其更改为如下所示:(删除了“。”)

<script src="/bundle.js"></script>

它完全为我修复了这个错误。

于 2016-05-16T04:27:34.137 回答