![](/img/trans.png)
[英]Laravel - How do i use the Return value of a controller in Javascript?
[英]How do I use JavaScript fetch in Laravel 8?
問題:因此,每當我單擊激活 Javascript 代碼的 HTML 按鈕時,我都會在控制台中收到一條錯誤消息: POST http://007.0.0.1 (狀態未知):
我試過的
我嘗試了不同的方法來讓變量工作,並返回一個視圖 JSON_ENCODE(),我一直在嘗試研究如何將 fetch 與 Laravel 一起使用,我覺得我錯過了一些明顯的東西。
這是我的 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 令牌不匹配的錯誤
您將需要在 fetch 請求中手動傳遞令牌
fetch('/payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'url': '/payment',
"X-CSRF-Token": document.querySelector('input[name=_token]').value
},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.