Как настроить WebPack DevServer для обработки запроса POST в React JS? - PullRequest
0 голосов
/ 29 июня 2018

Я интегрирую платежный шлюз в моем проекте React JS с маршрутами на стороне клиента.

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" component={PaytmResponse} />

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

        </BrowserRouter>
    );
}

Все вышеперечисленные маршруты: GET , кроме <PrivateRoute path="/paytm-response" component={PaytmResponse} />, это POST , маршрут.

Когда оплата завершена, платежный шлюз отправляет данные формы на этот маршрут POST.

Но я получаю сообщение об ошибке.

enter image description here

Ошибка говорит cannot POST /paytm-response.

Для сервера разработки я использую webpack dev server. Для производственного сервера я настроил экспресс-сервер, а для производства он работает без проблем.

Но я заметил, что webpack dev server не может обработать запрос POST с моей текущей конфигурацией веб-пакета.

webpack.config.js

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

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/'
        }
    }
}

Я гуглил по этой проблеме, обнаружил, что мне нужно настроить прокси в webpack.config.js.

Но, читая эту статью, я не смог понять рабочий процесс и способ его интеграции в файл конфигурации.

Примечание : Это мой первый проект React, поэтому я скопировал часть конфигурации в webpack.config.js

1 Ответ

0 голосов
/ 29 июня 2018

Webpack-dev-server - это маленький сервер Node.js Express, который использует webpack-dev-middleware для обслуживания пакета webpack. Он также имеет маленькая среда выполнения, которая подключена к серверу через Sock.js.

Таким образом, вы можете улучшить свои возможности webpack-dev-server с помощью setup config:

devServer: {
    contentBase: path.join(__dirname, 'public'),
    historyApiFallback: true,
    publicPath: '/dist/',

    /*** Required changes ***/
    setup: function handleAPIRequest(app) {
       app.all('/paytm-response', (req, res) => {
         res.send("hello"); 
         // Or respond with the mock JSON data
       });
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...