无法在ReactJS构建中手动访问URL

问题描述 投票:1回答:1

我使用Webpack 4.2.0创建了构建。但是我没有登陆到index页面就无法直接访问URL。

我的WebPack配置:

var webpack = require('webpack');
const HtmlPlugin = require('html-webpack-plugin')
// require('react-select/dist/react-select.css')
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src/');
var CSS_DIR = path.resolve(__dirname,'public/css');
// const HtmlPlugin = require('html-webpack-plugin');

var config = {
  entry: APP_DIR + '/index.js',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  plugins: [
    // Configure HtmlPlugin to use our own index.html file
    // as a template.
    // Check out https://github.com/jantimon/html-webpack-plugin
    // for the full list of options.
    new HtmlPlugin({
      template: 'public/index.html'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    // new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.LoaderOptionsPlugin({
     minimize: true
   })
  ],
  module : {
    rules: [
      {
        test: /\.js$/,
         enforce: "pre",
         include : APP_DIR,
         exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
        include : CSS_DIR
      }
    ]
  }
};

module.exports = config;

Index.js

render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'));

APP.JS

 const Main = () => (
      <main>
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route exact path='/contact' component={Contact}/>
          <Route path='/listing' component={Listing}/>
          <Route path='/product/:id' component={Product}/>
        </Switch>
      </main>
    )

在Build文件夹中,创建了两个文件。

 - index.html
 - bundle.js

我使用http-server打开React Build

./node_modules/.bin/http-server build -p 3007

但是在浏览器中,如果我直接访问URL localhost:3007/contact,它将抛出404。

什么是正确的生产部署方式,可以通过网址www.reactapp.com/contact访问

reactjs build
1个回答
1
投票

您需要配置服务器以便为所有index.html请求提供GET服务。 ReactRouter只是更改导航历史记录,当路由更改时,您实际上不会离开页面。目前,您的服务器只是为index.html路线提供/页面。将其配置为在所有路由上提供页面服务,您可以通过直接访问其URL来访问路由。

© www.soinside.com 2019 - 2024. All rights reserved.