如何配置WebPack DevServer来处理React JS中的POST请求?

时间:2018-06-29 13:14:14

标签: javascript reactjs webpack

我正在将我的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无法用我当前的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中。

1 个答案:

答案 0 :(得分:1)

  

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