asp.net-mvc - Javascript 发布请求回调,从 .NET MVC 控制器重定向
问题描述
我正在将 PayPal 结帐与电子商务解决方案集成,在 PayPal 成功创建 PayPal 订单/付款后,我执行一些服务器端处理,最终RedirectResult
从我的控制器返回一个(带有相应的付款失败或成功的 URL),返回到客户端/前端。
我在下面有以下代码,并希望它自动重定向,但不会发生重定向。
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [{
amount: {
value: '5.20',
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
});
}).catch(error=>console.log("Error capturing order!", error));
}
}).render('#paypal-button-container');
如果我使用下面的代码显式重定向,则执行该操作。
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
}).then(function () { window.location.replace('https://www.google.co.uk') });
}).catch(function (error) {
console.log("Error capturing order!", error);
window.location.replace('https://www.bbc.co.uk');
});
}
基本上,我想知道为什么 fetch 重定向不遵循从我的控制器返回的重定向。控制器重定向以获得完整的完整性:
return new RedirectResult("/checkout/thank-you") ;
解决方案
让我试着改写你的问题
您想知道为什么在您做出 a 之后浏览器没有重定向fetch
- 即使fetch
api 响应是RedirectResult
原因很简单,你在 中发出了请求fetch
,这意味着你正在发出ajax请求(因此浏览器不会改变)
您将 设置redirect
为follow
,这意味着在第一个请求之后(即从 获取响应之后
/umbraco/surface/PayPalPayment/process
),它将跟随到 url/checkout/thank-you
所以,您得到的then()
将是响应/checkout/thank-you
所以总的来说,它确实遵循了响应,但可能不是你期望的方式(遵循 ajax 请求,而不是浏览器更改页面)
如果您想要的是重定向到特定页面,则在成功调用之后/umbraco/surface/PayPalPayment/process
然后做:
- 修改您的后端以返回
JsonResult
url 而不是RedirectResult
return Json(new {redirectUrl = "/checkout/thank-you"});
- 用于
then
重定向
// other code omitted
.then(function (response) { return response.json(); })
.then(function (data) {window.location.replace(data.redirectUrl)});