【问题标题】:pass a parameter to a node application using POST使用 POST 将参数传递给节点应用程序
【发布时间】:2021-02-05 16:34:51
【问题描述】:

我正在运行以下节点应用程序(仅相关部分):

app.post("/create_customer_portal_session",async (req, res) => {
    const {customerId} = req.body;
    var session = await stripe.billingPortal.sessions.create({
        customer: customerId,
        return_url: 'https://****.com/account.php',
    });
    res.send(session);
});

如果我输入customer:'<customer id manually inserted>',它运行良好,但如果我尝试从请求中获取 customerId 的值,它就不行。 我错过了什么?

在客户端我有:

$('#portal').click(function(e){
        var customerId='<?php echo $stripe_customer;?>';
        e.preventDefault();
        $.post('https://****.com/store/create_customer_portal_session', {customerId:customerId},function( data ) {
            window.location.href = data.url;
        });         
    });

【问题讨论】:

  • request.body 的值是多少?
  • 也许这是一个愚蠢的问题,但我该如何检查呢?
  • 你可以用console.log打印出来
  • 您的页面实际上是由 PHP 服务器托管的吗?您共享了用 Node 编写的后端代码(并将问题标记为express),所以&lt;?php echo 的存在让我有点困惑。
  • 我有一个 Lamp 堆栈,我在其中对节点服务器执行 Ajax 调用。 @karllekko

标签: node.js express stripe-payments


【解决方案1】:

由于我没有使用 body-parser,我不得不切换到这个有效的代码:

    $('#portal').click(function(e){
        var customerId='<?php echo $stripe_customer;?>';
        e.preventDefault();
        /*$.get('https://thesmartred.com/store/create_customer_portal_session', {customerId:customerId},function( data ) {
            window.location.href = data.url;
        });*/
        fetch("https://***.com/store/create_customer_portal_session", {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              customerId: customerId
            })
        }).then(function(result) {
            return result.json();
            window.location.href=result.url;
        });
    });

所以我可以在body中传递参数,避免使用body-parser。

【讨论】:

    【解决方案2】:

    你可以这样试试,

       const bodyParser = require("body-parser");
    
        app.use(bodyParser.json());
      
        app.use(bodyParser.urlencoded({ extended: false }));
    
       app.post("/create_customer_portal_session",async (req, res) => {
          const {customerId} = req.body;
          var session = await stripe.billingPortal.sessions.create({
            customer: customerId,
            return_url: 'https://****.com/account.php',
          });
          res.send(session);
       });
    

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 2012-12-24
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多