如何从外部 API 调用重定向我的前端 React 应用程序
How Do I Redirect My Frontend React Application From External API Call
我正在构建一个小型项目,我正在使用一个名为 Paystack 的支付处理器。通常,当用户发起支付时,支付处理器会为当前支付交易生成唯一的 link。所有支付处理器请求都在后端设置,我基本上使用 NodeJS 和 Express。现在我当前的问题是使用生成的 link 将前端重定向到支付网关。处理代码基本上是这样的。
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization:
"Bearer ApiKey",
},
};
try {
const res = await axios.post(
`${API_URL}/payment/paystack/pay/${ref}`,
config
);
console.log(res);
} catch (error) {
console.log(error);
}
};
res
的结果就是生成的link。如何让我的前端转到生成的 link?
如有任何帮助,我们将不胜感激。谢谢。
您可以将 link 分配给 window.location
,让您的浏览器处理其余部分。
window.location = link;
如果是 React 应用程序 link,请使用 React 历史记录。
对于 React class 组件:
this.props.history.push(url);
对于 React 挂钩:
import { useHistory } from "react-router-dom";
...
const history = useHistory();
...
history.push(url);
如果它是外部的 link,你不应该使用 React 的东西。只需使用 window.location
:
window.location.href = url;
您可以简单地调用 window.open()
并将 link 作为参数传递。例如
window.open("https://www.w3schools.com");
或者您可以使用 react-router
我正在构建一个小型项目,我正在使用一个名为 Paystack 的支付处理器。通常,当用户发起支付时,支付处理器会为当前支付交易生成唯一的 link。所有支付处理器请求都在后端设置,我基本上使用 NodeJS 和 Express。现在我当前的问题是使用生成的 link 将前端重定向到支付网关。处理代码基本上是这样的。
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization:
"Bearer ApiKey",
},
};
try {
const res = await axios.post(
`${API_URL}/payment/paystack/pay/${ref}`,
config
);
console.log(res);
} catch (error) {
console.log(error);
}
};
res
的结果就是生成的link。如何让我的前端转到生成的 link?
如有任何帮助,我们将不胜感激。谢谢。
您可以将 link 分配给 window.location
,让您的浏览器处理其余部分。
window.location = link;
如果是 React 应用程序 link,请使用 React 历史记录。
对于 React class 组件:
this.props.history.push(url);
对于 React 挂钩:
import { useHistory } from "react-router-dom";
...
const history = useHistory();
...
history.push(url);
如果它是外部的 link,你不应该使用 React 的东西。只需使用 window.location
:
window.location.href = url;
您可以简单地调用 window.open()
并将 link 作为参数传递。例如
window.open("https://www.w3schools.com");
或者您可以使用 react-router