历史记录ApiFallback在Webpack开发服务器中不起作用

svujldwt  于 2023-04-30  发布在  Webpack
关注(0)|答案(9)|浏览(83)

我在React Router中使用Webpack dev server和browserHistory,通过HTML5历史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')
            })
        ]
    });
}

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>

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

包.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"
  }
}

我尝试在配置中更改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/'
},
cld4siwp

cld4siwp1#

我今天也遇到同样的问题。让我们在webpack中配置。js:output.publicPath等于devServer。历史ApiFallback.index和指出html文件路由。我的webpack-dev-server版本是1。10.1、做得很好 www.example.com 不起作用,你必须指出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'
        },
    },
};

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

k97glaaz

k97glaaz2#

output: {
    ...
    publicPath: "/"
  },

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

ivqmmu1c

ivqmmu1c3#

我遇到了这个问题,只能使用webpack 4中的index: '/'来修复它。20.2

historyApiFallback: {
            index: '/'
        }
7xllpg7q

7xllpg7q4#

这里有一件非常棘手的事情!
404可以是两个完全不同的东西。您可以打开Chrome的网络选项卡,查看是初始请求是404,还是其中的资产。
如果你不怕终端,你也可以做curl -v http://localhost:8081/product来查看实际的HTTP响应代码。

用例1:初始HTML页面404

这是使用historyFallbackApi的设置不正确的情况。
通常只有historyApiFallback: true才能在Webpack的devServer配置中工作。然而,如果你碰巧有一个自定义的output文件夹,你必须将historyApiFallbackindex属性设置为相同的路径,就像这个问题的其他答案(如jsdeveloper'sechzin's)所建议的那样。

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

这个很有趣!
在这种情况下,你实际上得到了初始的HTML(i。例如,如果您在URL之前添加view-source:以成为view-source:http://localhost:8081/admin,您会看到HTML,和/或curl命令显示HTML),但页面在浏览器中无法工作。

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

但是,如果您的资产路径是相对的(例如:例如,在view-source中,您看到<script src="vendor.js"></script>并且您正在着陆的路径与index(e.例如,当主服务器位于http://localhost:8081/admin时,您试图加载http://localhost:8081/admin/user/12/summary),发生的情况是它无法找到。js文件来获取JavaScript代码。(在我的情况下http://localhost:8081/admin/user/12/vendor.js

请注意,这里处理HTML5历史的路由器(react router或vue router)都知道如何在初始加载时初始化到document.location.href的内部路径。但是,它不知道正确更新资产路径的“根”在哪里。(也许这不是他的工作,在责任方面。)因此,资产的路径将基于URL的路径计算,而不是index.html的路径!因此,对于没有绝对/前缀的src="vendor.js",它会尝试查找/admin/user/12/vendor.js而不是/vendor.js
这里你需要做的是确保WebPack的output路径是绝对路径,并且以/开始,所以不管登陆URL是什么,它总是可以工作的。也就是说,在HTML源代码中它总是<script src="/vendor.js"></script>
为此,您必须将output.publicPath设置为绝对路径(带或不带域)。您可以通过上面的view-source:curl技术验证这一点。:)

7ajki6be

7ajki6be5#

参考: www.example.com
这适用于任何React路由器
必须添加historyApiFallback: true

module.exports = {
    cache: true,
    entry: "./index.js",
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'public')
    },
    context: SRC,
    devServer: {
        contentBase: path.resolve(__dirname, 'public/assets'),
        stats: 'errors-only',
        open: true,
        port: 8080,
        compress: true,
        historyApiFallback: true
    },
...
}
ee7vknir

ee7vknir6#

如果你发现某些路径有效,而其他路径无效,你可能会触犯“点规则”。根据文件:
当在路径中使用点时(与Angular常见),您可能需要使用disableDotRule

webpack.config.js

module.exports = {
  //...
  devServer: {
    historyApiFallback: {
      disableDotRule: true,
    },
  },
};
zsbz8rwp

zsbz8rwp7#

对我来说,这个设置工作了:

module.exports = {
    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
        filename: 'bundle-main.js'
    },

    devServer: {
    /* Telling the server to fallback to index.html if the route is not found at the backend server */
      historyApiFallback: true,
    }
};
utugiqy6

utugiqy68#

在webpack. config中。js只是添加这些行

devServer: {
    open: true,
    historyApiFallback: true,
   allowedHosts: 'all',
   hot: true
    
  },

并添加-〉//前缀:[“http://your url:8081/"]它运行得很好。

i34xakig

i34xakig9#

这个代码为我工作。我得到404.html

devServer: {
    static: {
      directory: "./dist",
    },
    historyApiFallback: {
      rewrites: [
        { from: /^\/$/, to: './index.html' },
        { from: /./, to: './404.html' }
      ]
    }
  },

相关问题