user1161310
user1161310

Reputation: 3139

cannot POST /payment (Node.js and Stripe)

I've embedded stripes checkout in a file called payment.ejs

<form action="" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_ODW7OJfVhlRJEgFY0ppWzwEE"
    data-amount="2000"
    data-name="Demo Site"
    data-description="2 widgets ($20.00)"
    data-image="/128x128.png">
  </script>
</form>

I visit the page and enter in a credit card that gets accepted. However, I then get the error

Cannot POST /payment

in my app.js i have

 app.post('payment', function(req, res){
    //stripe
        console.log('posted')

    var stripeToken = req.body.stripeToken;
    var charge = stripe.charges.create({
      amount: 1000, // amount in cents, again
      currency: "usd",
      card: stripeToken,
      description: "[email protected]"
    }, function(err, charge) {
      if (err && err.type === 'StripeCardError') {
        console.log("CARD DECLINED");
        res.send('error')
      }
      else {
          console.log("CARD ACCEPTED");
          res.send('ok')

      }
    });
 });

As per the instructions. I don't see whats wrong here. Any ideas?

Upvotes: 0

Views: 4318

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

Routes should include the preceding /:

app.post('/payment', function (req, res) {
    //    ^

    // ...
});

ExpressJS' routing is based in part on matching the path of the requested url, which includes each / from the "root" (after the hostname and port). The other part is the method.

app.use(function (req, res, next) {
    console.log(req.method); // "POST"
    console.log(req.path);   // "/payment"
                             //  ^
    next();
});

Note: Whether a trailing / or lack of is required to match depends on whether strict routing or a Router's strict option is enabled.

Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router.

Upvotes: 3

Related Questions