You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express提交表单后重定向至React组件的实现问题

Got it, let's figure out how to get that redirect working after your Stripe charge goes through. Since you're running a React single-page app (SPA) with Express serving your static files and catching all GET requests to return index.html, we have two straightforward approaches to redirect to your target React component.

方案1:后端直接重定向到前端路由路径

Since your Express app already handles all GET requests by returning the React app's index.html, you can just redirect to the route that maps to your desired React component once the Stripe charge succeeds. The key here is to properly handle the async Stripe API call (since stripe.charges.create is asynchronous).

Here's how to update your Express /charge endpoint:

app.post('/charge', async (req, res) => { // Add async keyword here
  try {
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    const charge = await stripe.charges.create({
      amount: req.body.totalAmount * 100,
      currency: 'eur',
      source: req.body.stripeToken,
      description: 'Your charge description here'
    });

    // Redirect to your React component's route (e.g., /payment-success)
    res.redirect('/payment-success');
  } catch (error) {
    // Handle errors (e.g., redirect to an error page)
    console.error('Charge failed:', error);
    res.redirect('/payment-error');
  }
});

Then, make sure your React Router has a route set up for /payment-success that renders your target component:

// In your React Router setup (e.g., App.js)
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import PaymentSuccess from './components/PaymentSuccess';
import PaymentError from './components/PaymentError';

function App() {
  return (
    <Router>
      <Routes>
        {/* Your other existing routes */}
        <Route path="/payment-success" element={<PaymentSuccess />} />
        <Route path="/payment-error" element={<PaymentError />} />
      </Routes>
    </Router>
  );
}

方案2:返回JSON响应,让前端处理跳转(更贴合SPA的做法)

If you want to avoid a full page refresh (which is more typical for SPAs), you can have your Express endpoint return a JSON success/error response, then use React Router's navigation tools to switch to the target component on the frontend.

First, update your Express endpoint:

app.post('/charge', async (req, res) => {
  try {
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    const charge = await stripe.charges.create({
      amount: req.body.totalAmount * 100,
      currency: 'eur',
      source: req.body.stripeToken,
      description: 'Your charge description here'
    });

    res.json({ success: true, message: 'Charge completed successfully' });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

Then, in your React component where you submit the form (using fetch or axios):

import { useNavigate } from 'react-router-dom';

function CheckoutForm() {
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const totalAmount = formData.get('totalAmount');
    const stripeToken = formData.get('stripeToken');

    try {
      const response = await fetch('/charge', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `totalAmount=${totalAmount}&stripeToken=${stripeToken}`
      });

      const result = await response.json();
      if (result.success) {
        // Navigate to the success component without page reload
        navigate('/payment-success');
      } else {
        navigate('/payment-error');
      }
    } catch (error) {
      console.error('Submission failed:', error);
      navigate('/payment-error');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Your form fields for amount, Stripe token, etc. */}
      <button type="submit">Complete Payment</button>
    </form>
  );
}

Important Notes:

  • Always handle errors! Both in the Express backend and React frontend—you don't want users stuck with no feedback if the charge fails.
  • The first approach triggers a full page reload (server-side redirect), which works but is less "SPA-like". The second approach keeps navigation client-side for a smoother user experience.
  • Ensure your React Router uses BrowserRouter (not HashRouter) so that the server-side routes are properly handled by Express's get * rule.

内容的提问来源于stack exchange,提问作者Victor Garcia Civera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:29:52