当试图直接访问它们时,React网站w /表示不在生产中加载路由,在dev中工作正常

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

所以基本上我只是决定将我的网站上传到服务器,虽然搞乱了我决定尝试访问其中一条路线'/ singup',这引发了以下错误:404 error如果你试图通过主要路线访问它'/'网站运行正常。如果我从我的电脑运行它,该网站也可以在localhost上正常工作。

我在dreamhost静态Web服务器上托管应用程序。

有谁知道如何解决这个问题?

下面是我的快递server.jswebpackindex.jsindex.html配置,我也使用react router 4和webpack 3.5.5。

如果您需要更多信息,请告诉我们!

server.js

const bodyParser = require('body-parser');
const express = require('express');
const historyApiFallback = require('connect-history-api-fallback');
const mongoose = require('mongoose');
const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const cors = require('cors');
const fallback = require('express-history-api-fallback')

const config = require('../config/config');
const webpackConfig = require('../webpack.config');

const isDev = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 8080;


// Configuration
// ================================================================================================

// Set up Mongoose
mongoose.connect(isDev ? config.db_dev : config.db, {
  useMongoClient: true
});
mongoose.Promise = global.Promise;

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// app.use(fallback(path.resolve(__dirname, './dist/index.html')));

// API routes
app.use(cors());


if (isDev) {
  const compiler = webpack(webpackConfig);

  app.use(historyApiFallback({
    verbose: false
  }));

  app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    contentBase: path.resolve(__dirname, '../client/public'),
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false
    }
  }));

  app.use(webpackHotMiddleware(compiler));
  app.use(express.static(path.resolve(__dirname, '../dist')));
} else {
  app.use(historyApiFallback({
    verbose: true
  }));
  app.use(express.static(path.resolve(__dirname, '../dist')));
  // app.use(fallback(path.resolve(__dirname, './dist/index.html')));
  app.get('*', function (req, res) {
    res.sendFile(path.resolve(__dirname, '../dist/index.html'));
    res.end();
  });
}

app.listen(port, '0.0.0.0', (err) => {
  if (err) {
    console.log(err);
  }

  console.info('>>> 🌎 Open http://0.0.0.0:%s/ in your browser.', port);
});

module.exports = app;

webpack.prod.js

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

const helpers = require('./helpers');
const commonConfig = require('./webpack.common');

module.exports = merge(commonConfig, {
  output: {
    filename: 'js/[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js',
    historyApiFallback: true
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
        screw_ie8: true
      },
      output: {
        comments: false
      }
    })
  ]
});

webpack.common.js

const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const helpers = require('./helpers');

const NODE_ENV = process.env.NODE_ENV;
const isProd = NODE_ENV === 'production';

module.exports = {
  entry: {
    'app': [
      helpers.root('client/app/index.js')
    ]
  },

  output: {
    path: helpers.root('dist'),
    publicPath: '/'
  },

  resolve: {
    extensions: ['.js', '.json', '.css', '.scss', '.html'],
    alias: {
      'app': 'client/app'
    }
  },

  module: {
    rules: [
      // JS files
      {
        test: /\.jsx?$/,
        include: helpers.root('client'),
        loader: 'babel-loader'
      },

      // SCSS files
      {
        test: /\.(scss|css)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                'sourceMap': true,
                'importLoaders': 1
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                plugins: () => [
                  autoprefixer
                ]
              }
            },
            'sass-loader'
          ]
        })
      }
    ]
  },

  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(NODE_ENV)
      }
    }),

    new HtmlWebpackPlugin({
      template: helpers.root('client/public/index.html'),
      inject: 'body'
    }),

    new ExtractTextPlugin({
      filename: 'css/[name].[hash].css',
      disable: !isProd
    }),

    new CopyWebpackPlugin([{
      from: helpers.root('client/public')
    }])
  ]
};

webpack.config.js

switch (process.env.NODE_ENV) {
  case 'prod':
  case 'production':
    module.exports = require('./config/webpack.prod');
    break;

  case 'dev':
  case 'development':
  default:
    module.exports = require('./config/webpack.dev');
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Travip</title>

  <link rel="icon" type="image/png" href="/assets/img/logo.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>
<body>
  <div id="app" href="/"></div>
  <!-- Start of HubSpot Embed Code -->
    <script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/4314456.js"></script>
  <!-- End of HubSpot Embed Code -->
</body>
</html>

index.js

import React from 'react';
import { render } from 'react-dom';

import {
  Router,
  Route,
  Switch
} from 'react-router-dom';
import history from './history';

import App from './components/App/App';
import NotFound from './components/App/NotFound';

import Home from './components/Home/Home';

import SignUp from './components/LandingPage/SignUp';

import './styles/globalStyle.js';
import './../../node_modules/toastr/build/toastr.min.css';
import 'semantic-ui-react';
import 'semantic-ui-css';

render((
  <Router history={history}>
    <App>
      <Switch>
        <Route exact path="/" render={(props) => <Home {...props}/>}/>
        <Route path="/signup" render={(props) => <SignUp {...props}/>}/>
        <Route render={NotFound}/>
      </Switch>
    </App>
  </Router>
), document.getElementById('app'));
javascript reactjs express webpack react-router
1个回答
0
投票

您需要将所有流量重定向到您的应用,以便让它处理路由。

静态的 :

例如,在S3上,您将错误文档定义为index.html

服务器:

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
© www.soinside.com 2019 - 2024. All rights reserved.