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

Angular Universal(Angular 5.2.8)下支付回调POST数据转发后端方案咨询

Solution for Forwarding Payment Callback POST Requests with Angular Universal

Hey there, let's work through this payment callback issue you're hitting with Angular 5.2.8 + nguniversal/express-engine 5.0.0-beta.6. I’ve dealt with similar Universal + webhook scenarios before, so here’s a solid, step-by-step solution that should get this working for you:

Core Idea

Since you’re using Angular Universal, your Express server acts as the entry point for all incoming requests. The fix is to add a dedicated POST route directly in your Express server to catch the payment service’s callback, attach the user’s credentials, and forward the request to your backend. This bypasses Angular’s routing entirely (which can’t handle POST requests natively).

Step 1: Update Your Express Server (server.ts)

First, modify your server file to add the callback route before setting up the Angular Universal engine. This ensures Express handles the POST request before it gets passed to Angular.

  1. First, install any required dependencies (if you don’t have them already):

    npm install cookie-parser
    

    We’ll use this to access user credentials stored in cookies (the most reliable way to pass auth from client to server in Universal).

  2. Update server.ts with the callback route:

    import * as express from 'express';
    import { join } from 'path';
    import { ngExpressEngine } from '@nguniversal/express-engine';
    import cookieParser from 'cookie-parser'; // Import cookie parser
    
    // Initialize Express app
    const app = express();
    app.use(cookieParser()); // Enable cookie parsing
    app.use(express.json()); // Parse JSON request bodies (critical for POST data)
    
    // 1. Add the payment callback POST route FIRST
    app.post('/payment-callback', async (req, res) => {
      try {
        // Get user credentials from cookies (adjust the key to match your app's token name)
        const userAuthToken = req.cookies['your-app-auth-token'];
    
        // Forward the request to your backend
        const backendResponse = await fetch('https://your-own-backend.com/payment-webhook', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${userAuthToken}` // Attach user's auth token
          },
          body: JSON.stringify(req.body) // Pass the full payment callback data
        });
    
        const backendData = await backendResponse.json();
    
        // Send the backend's response back to the payment service
        res.status(backendResponse.status).json(backendData);
      } catch (error) {
        console.error('Failed to forward payment callback:', error);
        // Important: Always return 200 OK to the payment service to stop retries
        res.status(200).send('Callback received successfully');
      }
    });
    
    // 2. Now set up Angular Universal (keep your existing code here)
    app.engine('html', ngExpressEngine({
      bootstrap: AppServerModuleNgFactory,
      providers: [
        // Your existing Universal providers
      ]
    }));
    
    app.set('view engine', 'html');
    app.set('views', join(DIST_FOLDER, 'browser'));
    
    // Serve static files and handle Angular routes
    app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
    app.get('*', (req, res) => {
      res.render('index', { req });
    });
    
    // Start server (keep your existing listen code)
    const PORT = process.env.PORT || 4000;
    app.listen(PORT, () => {
      console.log(`Node server listening on http://localhost:${PORT}`);
    });
    

Step 2: Configure the Payment Service’s Callback URL

Set your payment service’s callback URL to point to this new Express route:
https://your-frontend-domain.com/payment-callback

Step 3: Test the Flow

Use a tool like Postman to simulate a POST request to your /payment-callback endpoint. Include sample payment data in the request body and a valid auth cookie to verify:

  • The request is correctly forwarded to your backend
  • The user’s auth token is included in the headers
  • The payment service receives a 200 OK response

Why Your Previous Attempts Might Have Failed

If you tried adding an Express POST route before and it didn’t work, these are the most common culprits:

  • Route Order: You added the POST route after Angular’s * route, so Express passed the request to Angular instead of handling it directly.
  • Missing Request Parsing: You didn’t use express.json() to parse the POST body, so req.body was undefined.
  • Auth Credential Storage: You tried accessing localStorage on the server (which doesn’t exist in Node.js). Always use cookies for auth in Angular Universal.

内容的提问来源于stack exchange,提问作者Can Bakış

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:16:15