簡體   English   中英

盡管將webpack-dev-server的historyApiFallback設置為true,但仍在我的React應用中接收404

[英]Receiving 404s in my React app despite setting historyApiFallback to true for webpack-dev-server

我正在開發一個React應用程序,該應用程序當前在http:// localhost:3000 /上提供 ,我希望在它上面進行一些基本的路由。 我一直在嚴格遵循Redux指南,但是似乎無法正確設置后備網址。 應用指南中描述的Webpack更改后,訪問任何鏈接(例如http:// localhost:3000 / test)將導致404響應和“無法獲取/ test”錯誤。 定義路由的index.jsx文件如下所示:

index.jsx

import 'babel-polyfill';
import React from 'react';
import { Router, Route, browserHistory } from 'react-router';
import { createStore, applyMiddleware, compose } from 'redux';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import App from './components/App';
import rootReducer from './reducers/';

/* eslint-disable no-underscore-dangle */
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
/* eslint-enable */

const store = createStore(rootReducer, {}, composeEnhancers(
  applyMiddleware(thunkMiddleware),
));

if (module.hot) {
  module.hot.accept();
}

render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/(:filter)" component={App} />
    </Router>
  </Provider>,
  document.getElementById('root'),
);

在webpack配置中,我嘗試使用historyApiFallback: true以及historyApiFallback: { index: 'index.html' }以及index屬性值的一些變化。 這是完整的配置:

webpack.config.js

var webpack = require('webpack');
var path = require('path');

module.exports = {
  debug: true,
  devtool: '#eval-source-map',
  context: path.join(__dirname, 'src'),
  resolve: {
    root: path.resolve('./src'),
    extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'],
  },
  devServer: {
    historyApiFallback: {
      index: '/',
    },
  },
  entry: [
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client',
    './index',
  ],
  output: {
    path: path.join(__dirname, 'src'),
    publicPath: '/',
    filename: 'bundle.js',
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] },
    ],
  },
};

有什么想法可能會出問題嗎?

編輯:還有一些與BrowserSync 可能相關的配置:

app.js

/**
 * Require Browsersync along with webpack and middleware for it
 */
var browserSync = require('browser-sync');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');

/**
 * Require ./webpack.config.js and make a bundler from it
 */
var webpackConfig = require('./webpack.config');
var bundler = webpack(webpackConfig);

/**
 * Run Browsersync and use middleware for Hot Module Replacement
 */
browserSync({
  server: {
    baseDir: 'src',

    middleware: [
      webpackDevMiddleware(bundler, {
        // IMPORTANT: dev middleware can't access config, so we should
        // provide publicPath by ourselves
        publicPath: webpackConfig.output.publicPath,

        // pretty colored output
        stats: { colors: true },

        // for other settings see
        // http://webpack.github.io/docs/webpack-dev-middleware.html
      }),

      // bundler should be the same as above
      webpackHotMiddleware(bundler),
    ],
  },

  // no need to watch '*.js' here, webpack will take care of it for us,
  // including full page reloads if HMR won't work
  files: [
    'src/css/*.css',
    'src/*.html',
  ],
});

使用browserHistory ,必須適當配置server以在所有routed路徑中提供服務:

https://github.com/ReactTraining/react-router/blob/v2.0.0-rc5/docs/guides/basics/Histories.md#configuring-your-server

但是,如果您不想僅放置快速服務器來進行熱重裝,請使用以下命令:

webpack-dev-server -d --history-api-fallback --hot --inline --progress --colors

盡管我無法在本地開發環境中運行browserHistory,但短期內切換到hashHistory是一個足夠好的解決方案。

服務器必須返回主react頁面,如果您將react app托管在IIS上,則react將進行植根,只需添加一個包含以下內容的web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" path="/" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>

這將告訴IIS服務器返回主索引頁而不是404錯誤,並且不需要使用哈希歷史記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM