Реактивный маршрут работает правильно при использовании с <Link>, но не работает при перенаправлении из webpack.config.js - PullRequest
0 голосов
/ 30 июня 2018

В моем реактивном проекте я использую маршрутизацию на стороне клиента с использованием React Router DOM v4.

Ссылка на видео с моей постановкой задачи: https://drive.google.com/file/d/1nHY-dKxZvDylF5GQUTK02I8Mam1d5eru/view?usp=sharing

Я создал такой маршрут <Route path="/pg-response/:status" component={PaytmResponse} exact={true}/>

Вот мой файл AppRouter.js

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import {TransitionGroup, CSSTransition} from 'react-transition-group';
import PrivateRoute from './PrivateRoute';

import HomePage from './../components/HomePage';
import AboutUs from './../components/AboutUs';
import ContactUs from './../components/ContactUs';
import PageNotFound from './../components/PageNotFound';
import RestaurantList from '../components/RestaurantList';
import Foodcourt from '../components/Foodcourt';
import RestaurantMenu from '../components/RestaurantMenu';
import UserDetails from '../components/UserDetails';
import OrderConfirmation from '../components/OrderConfirmation';
import CustomerAccount from '../components/CustomerAccount';
import Logout from '../components/sections/Logout';
import RedirectPG from '../components/sections/RedirectPG';
import SodexoResponse from '../components/sections/SodexoResponse';
import OrderFail from '../components/OrderFail';
import PaytmResponse from '../components/sections/PaytmResponse';


export default () => {
    return (
        <BrowserRouter>
            <Route render={({location}) => (
                <TransitionGroup>
                    <CSSTransition key={location.key} timeout={300} classNames="fade">
                        <Switch location={location}>
                            <Route path="/" component={HomePage} exact={true}/>
                            <Route path="/about" component={AboutUs} />
                            <Route path="/contact" component={ContactUs} />
                            <Route path="/restaurants" component={RestaurantList} />
                            <Route path="/foodcourt" component={Foodcourt} />
                            <Route path="/select-menu" component={RestaurantMenu} />
                            <PrivateRoute path="/user-details" component={UserDetails} />
                            <PrivateRoute path="/order-confirmation" component={OrderConfirmation} />
                            <PrivateRoute path="/payment-failed" component={OrderFail} />
                            <PrivateRoute path="/my-account" component={CustomerAccount} />
                            <PrivateRoute path="/logout" component={Logout} />
                            <PrivateRoute path="/redirect-to-pg" component={RedirectPG} />
                            <PrivateRoute path="/sodexo-response" component={SodexoResponse} />
                            <PrivateRoute path="/paytm-response"/>
                            <Route path="/pg-response/:status" component={PaytmResponse} exact={true}/>

                            <Route component={PageNotFound} />
                        </Switch>
                    </CSSTransition>
                </TransitionGroup>
            )} />

        </BrowserRouter>
    );
}

Проблема в том, что когда я иду по этому маршруту с <Link>, щелчок работает без проблем. Но когда я иду по этому пути, перенаправляя из файла webpack.config.js, я получаю много ошибок.

Вот мой файл webpack.config.js

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const url = require('url');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');

const app = express();

module.exports = (env) => {

    const isProduction = env === 'production';
    const CSSExtract = new ExtractTextPlugin('styles.css');

    return {
        entry: ['babel-polyfill','./src/app.js'],
        output: {
            path : path.join(__dirname, 'public', 'dist'),
            filename: 'bundle.js'
        },
        module: {
            rules: [
                {
                    loader: 'babel-loader',
                    test: /\.js$/,
                    exclude: /node_modules/
                },
                {
                    test: /\.css$/,
                    use: CSSExtract.extract({
                        fallback: 'style-loader',
                        use: [
                            {
                                loader: 'css-loader',
                                options: {
                                    sourceMap: true
                                }
                            }
                        ]
                    })
                },
                {
                    test: /\.(png|jp(e*)g|gif|svg)$/,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                limit: 8000,
                                name: 'images/[hash]-[name].[ext]',
                                publicPath: '/dist/'
                            }
                        }
                    ]
                },
                {
                    test: /\.(woff|woff2|eot|ttf|otf|mp4)$/,
                    use: [
                        {
                            loader: "file-loader",
                            options: {
                                name: 'files/[hash]-[name].[ext]',
                                publicPath: '/dist/'
                            }
                        }
                    ]

                }
            ]
        },
        plugins: [
            CSSExtract,
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                "window.jQuery": "jquery"
            })
        ],
        devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
        devServer: {
            contentBase: path.join(__dirname, 'public'),
            historyApiFallback: true,
            publicPath: '/dist/',
            setup: (app) => {
                app.use(bodyParser.urlencoded({ extended: true }));
                app.post('/paytm-response',(req, res) => {
                    res.redirect(`/pg-response/${req.body.STATUS}`);
                })
            }
        }
    }
}

Я также использую historyApiFallback: true. Тем не менее проблема существует.

1 Ответ

0 голосов
/ 06 июля 2018

После многих поисков я обнаружил, что внутри файла index.html я использовал относительный путь к скриптам и файлам CSS.

Я изменил их на абсолютный путь, и все работало нормально.

Это была не проблема веб-пакета или чего-то еще, просто проблема с тем, как скрипты и CSS-файлы импортировались в index.html файл.

...