首页 > 解决方案 > 如何配置 WebPack DevServer 来处理 React JS 中的 POST 请求?

问题描述

我正在将我的 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>
    );
}

以上所有路由都是G​​ET<PrivateRoute path="/paytm-response" component={PaytmResponse} />路由,除了POST路由。

付款完成后,支付网关将表单数据发布到此 POST 路由。

但我收到错误消息。

在此处输入图像描述

错误说cannot POST /paytm-response

对于开发服务器,我使用的是webpack dev server. 对于生产服务器,我已经配置了快速服务器,对于生产,它工作正常,没有任何问题。

但我注意到webpack dev server我当前的 webpack 配置无法处理 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 中的一些配置

标签: javascriptreactjswebpack

解决方案


webpack-dev-server 是一个小的 Node.js Express 服务器,它使用 webpack-dev-middleware 来提供 webpack 包。它还有一个小运行时,通过 Sock.js 连接到服务器。

setup所以基本上你可以通过使用config来增强你​​的 webpack-dev-server 能力:

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
       });
    }
}

推荐阅读