javascript - 如何在 Laravel 8 中使用 JavaScript 获取?

标签 javascript php laravel fetch laravel-8

问题:
因此,每当我单击激活 Javascript 代码的 HTML 按钮时,我都会在控制台中收到一条错误消息:
发布 http://127.0.0.1:8000/payment 419(未知状态)
我尝试过的
我尝试了不同的方法来让变量工作,用 View 返回它,JSON_ENCODE(),我一直在尝试研究如何在 Laravel 中使用 fetch,我觉得我错过了一些明显的东西。
这是我的 HTML 和 Javascript 代码:

<form action="/payment" method="POST">
@csrf
<button class="btn btn-primary py-3 px-4" id="checkout-button">Proceed to Checkout</button>
<script type="text/javascript">
    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe('pk_test_*******************');
    var checkoutButton = document.getElementById('checkout-button');

    checkoutButton.addEventListener('click', function() {
    // Create a new Checkout Session using the server-side endpoint you
    // created in step 3.
        fetch('/payment', {
            method: 'POST', 
            headers: {
               'Content-Type': 'application/json',
               'Accept': 'application/json',
               'url': '/payment',
            },
         })
         .then(function(response) {
             return response.json();
         })
         .then(function(session) {
             return stripe.redirectToCheckout({ sessionId: session.id });
         })
         .then(function(result) {
             // If `redirectToCheckout` fails due to a browser or network
             // error, you should display the localized error message to your
             // customer using `error.message`.
             if (result.error) {
                 alert(result.error.message);
             }
          })
          .catch(function(error) {
              //console.error('Error:', error);
          });
      });
</script>
</form>
这是我的路线:
Route::post('/payment', [StripePaymentController::class, 'payment']);
这是我的 Controller 方法:
    /* Sends the stripe key, and payment info to the stripe api, as long as the payment session */
    public function payment() {
        // Sets up the businesses secret key to receive the payment
        \Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        // Sets up payment method, and product information
        $session = \Stripe\Checkout\Session::create ([
            'payment_method_types' => ['card'],
            'line_items' => [[
              'price_data' => [
                'currency' => 'usd',
                'product_data' => [
                  'name' => 'T-shirt',
                ],
                'unit_amount' => 2000,
              ],
              'quantity' => 1,
            ]],
            'mode' => 'payment',
            'success_url' => 'http://127.0.0.1:8000/',
            'cancel_url' => 'http://127.0.0.1:8000/cart',
        ]);

        return response()->json(['id' => $session->id]);
    }

最佳答案

这是关于 CSRF token 不匹配的错误
您将需要在 fetch 请求中手动传递 token

fetch('/payment', {
    method: 'POST', 
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'url': '/payment',
        "X-CSRF-Token": document.querySelector('input[name=_token]').value
    },
})

关于javascript - 如何在 Laravel 8 中使用 JavaScript 获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65014796/

相关文章:

javascript - 使用 requestAnimationFrame 的 JavaScript 动画帧速率不稳定

php - Doctrine 2 PlainValue 预期

php - 使用 Laravel 将 youtube-dl 输出流式传输到 S3

java - 如何将 Eclipse 同时用于 Java 和 PHP?

php - 将 Laravel Web 应用程序复制到子域并分离数据库

php - laravel 组件类被忽略

javascript - 在 Loopback.io 远程方法中访问入站 HTTP header

javascript - d3 日历 View : how to put all into one svg instead of several svgs

javascript - Android 4.0浏览器溢出: scroll and touch/click events

php - 字符串运算,如二进制 AND