historyApiFallback在Webpack dev服务器中不起作用

Mat*_*att 21 javascript html5-history webpack react-router webpack-dev-server

在React Router中使用Webpack dev服务器和browserHistory来通过HTML5 History API操作url.historyapifallback-option在我的webpack配置文件中不起作用.刷新后http://localhost:8080/usershttp://localhost:8080/products我得到404.

webpack.config.js

var webpack = require('webpack');
var merge = require('webpack-merge');

const TARGET = process.env.npm_lifecycle_event;

var common = {
    cache: true,
    debug: true,
    entry: './src/script/index.jsx',
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    output: {
        sourceMapFilename: '[file].map'
    },
    module: {
        loaders: [
            {
                test: /\.js[x]?$/,
                loader: 'babel-loader',
                exclude: /(node_modules)/
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]
};

if(TARGET === 'dev' || !TARGET) {
    module.exports = merge(common,{
        devtool: 'eval-source-map',
        devServer: {
            historyApiFallback: true
        },
        output: {
            filename: 'index.js',
            publicPath: 'http://localhost:8090/assets/'
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify('dev')
            })
        ]
    });
}
Run Code Online (Sandbox Code Playgroud)

的index.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
        <title>Test</title>
    </head>
    <body>
        <div id="content">
            <!-- this is where the root react component will get rendered -->
        </div>
        <script src="http://localhost:8090/webpack-dev-server.js"></script>
        <script type="text/javascript" src="http://localhost:8090/assets/index.js"></script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

index.jsx

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, useRouterHistory, browserHistory, Link} from 'react-router';

class Home extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div>
          I am home component
          <Link to="/users" activeClassName="active">Users</Link>
          <Link to="/products" activeClassName="active">Products</Link>
        </div>;
  }
}

class Users extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div> I am Users component </div>;
  }
}

class Products extends Component{
  constructor(props) {
    super(props);
  }

  render() {
      return <div> I am Products component </div>;
  }
}

ReactDOM.render(
    <Router history={browserHistory} onUpdate={() => window.scrollTo(0, 0)}>
        <Route path="/" component={Home}/>
        <Route path="/users" component={Users} type="users"/>
        <Route path="/products" component={Products} type="products"/>
    </Router>
    , document.getElementById('content'));
Run Code Online (Sandbox Code Playgroud)

的package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.jsx",
  "scripts": {
    "start": "npm run serve | npm run dev",
    "serve": "./node_modules/.bin/http-server -p 8080",
    "dev": "webpack-dev-server -d --progress --colors --port 8090 --history-api-fallback"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "events": "^1.1.0",
    "jquery": "^2.2.3",
    "path": "^0.12.7",
    "react": "^15.0.2",
    "react-dom": "^15.0.2",
    "react-mixin": "^3.0.5",
    "react-router": "^2.4.0"
  },
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.8.0",
    "babel-loader": "^6.2.4",
    "babel-polyfill": "^6.8.0",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-register": "^6.8.0",
    "http-server": "^0.9.0",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1",
    "webpack-merge": "^0.12.0"
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图在我的配置中更改devServer,但它没有帮助:

devServer: {
    historyApiFallback: {
        index: 'index.html',
    }
},

devServer: {
    historyApiFallback: {
        index: 'index.js',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.html',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.js',
    }
},

devServer: {
    historyApiFallback: {
        index: 'http://localhost:8090/assets/index.js',
    }
},
output: {
    filename: 'index.js',
            publicPath: 'http://localhost:8090/assets/'
},
Run Code Online (Sandbox Code Playgroud)

小智 30

我今天遇到了同样的问题.让webpack.config.js中的config:output.publicPath等于devServer.historyApiFallback.index并指出html文件路由 .my webpack-dev-server版本是1.10.1并且运行良好.http://webpack.github.io/docs/webpack-dev-server.html#the-historyapifallback-option不起作用,你必须指出html文件路由.

例如

module.exports = {
    entry: "./src/app/index.js",
    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: 'build',
        filename: 'bundle-main.js'
    },
    devServer: {
        historyApiFallback:{
            index:'build/index.html'
        },
    },
};
Run Code Online (Sandbox Code Playgroud)

historyApiFallback.index指示当url路径与真实文件不匹配时,webpack-dev-server使用historyApiFallback.index中的文件配置在浏览器而不是404页面中显示.然后关于你的路线改变的所有事情让你的js使用react-router做.


jsd*_*per 14

我遇到了这个问题,只能使用index: '/'webpack 4.20.2修复它

        historyApiFallback: {
            index: '/'
        }
Run Code Online (Sandbox Code Playgroud)


Aid*_*din 10

这里发生了一件非常棘手的事情!

404 可以是下面两个完全不同的东西。您可以打开Chrome的网络选项卡,查看是否是初始请求404,或者其中的资产。

如果你不怕终端,你也可以curl -v http://localhost:8081/product查看实际的HTTP响应代码。

情况 1:初始 HTML 页面出现 404

这是historyFallbackApi设置不正确的情况。

通常只historyApiFallback: true应该在 Webpack 的配置中工作devServer。(来源)但是,如果您碰巧有一个自定义output文件夹,则必须将index的 属性设置historyApiFallback为同一路径,正如jsdeveloperechzin 等有关此问题的其他答案所建议的那样。

案例 2:资产上的 404(例如bundle.jsvendor.js

这个还蛮有趣的!

在这种情况下,您确实获得了初始 HTML(即,如果您view-source:在 URL 之前添加为view-source:http://localhost:8081/admin,您会看到您的 HTML,和/或curl命令显示 HTML),但该页面在浏览器中不起作用。

HistoryApiFallback所做的事情,听起来像是一个魔术,实际上只是将req.urlExpress 服务器设置为index.html文件,用于域内任何传入的 GET 请求。(源代码中的主要两行

但是,如果您的资产的路径是相对的(例如,在视图源中,您会看到<script src="vendor.js"></script>,并且您登陆的路径与索引的路径深度不同(例如,您尝试http://localhost:8081/admin/user/12/summary在主服务器运行时加载) at http://localhost:8081/admin),发生的情况是找不到 JavaScript 代码的 .js 文件。(就我而言http://localhost:8081/admin/user/12/vendor.js

在此输入图像描述

请注意,这里处理 HTML5 历史记录的任何路由器(react 路由器或 vue 路由器)都知道如何在document.location.href初始加载时初始化内部路径。但是,它不知道正确更新资产路径的“根”在哪里。(就责任而言,也许这甚至不是它的工作。)因此,资产的路径将根据 URL 的路径而不是 的index.html路径来计算!因此,对于src="vendor.js"没有绝对/前缀的情况,它会尝试查找/admin/user/12/vendor.js而不是/vendor.js.

这里您需要做的是确保outputWebPack 的路径是绝对路径并以 开头/,因此无论登陆 URL 是什么,它总是有效。即它总是<script src="/vendor.js"></script>在 HTML 源代码中。

为此,您必须设置output.publicPath为绝对路径(带或不带域)。您可以通过上面的view-source:curl技术来验证这一点。:)


ami*_*mit 9

output: {
    ...
    publicPath: "/"
  },
Run Code Online (Sandbox Code Playgroud)

添加公共路径为我解决了这个问题