簡體   English   中英

如何使用 express 和 axios 在瀏覽器上重定向和呈現從 API 響應 object 獲得的 url

[英]How to redirect and render the url gotten from an API response object on the browser using express and axios

我正在使用 paystack API 和 Axios 構建支付網關以發出 http 請求。

我使用了他們的 API 文檔並檢查了他們的 postman 集合以了解如何編寫代碼。

該代碼適用於 postman,因為每當我發送一個 post 請求以使用所需參數初始化事務時,我都會收到包含我需要的數據的響應 object(在本例中為 url)

問題是,我無法讓我的應用程序重定向到瀏覽器上響應數據 object 中包含的 url,我在瀏覽器 window 上不斷收到此錯誤

無法獲取/paystack/undefined

已經查找了問題,嘗試了一些可能的解決方案,從重構代碼到使用 async await 但它不起作用(除了可能會稍微提高響應速度)

這是代碼

Controller

const { default: axios } = require("axios");


exports.postForm = async (req, res) => { 
  
    await axios({ 
       method: 'post', 
       url: 'https://api.paystack.co/transaction/initialize', 
       headers: { 
          'Authorization': secretKey, 
          'Content-Type': 'application/json', 
          'cache-control': 'no-cache' 
       }, 
       data: { 
          "email": req.body.email, 
          "amount": req.body.amount 
       }
    }) 
    .then((response) => { 
       res.status(302).redirect(response.data.authorizaton_url) // it is supposed to go to the url inside the data object
       console.log(response.data) 
    }) 
    .catch((error) => { 
       console.log(error); 
    }); 
 };

試圖將 response.data 字符串化,但它沒有改變任何東西

航線

const express = require('express'); 
 const router = express.Router(); 
 const pay = require('../controllers/paymentController'); 
  
 router.get('/', pay.getForm); 
 router.post('/paystack/pay', pay.postForm);

Ps - 除非我將用戶重定向回我的應用程序以確認交易,否則 GET 路由無濟於事。 使用了另一個名為 Request 的 http 庫,它可以工作,但已被棄用。

您可以在 paystack 上設置回調 url 以在成功付款時重定向用戶,您可以在后台查看。 網絡掛鈎 url

如果這沒有幫助,您可以考慮使用 res.status(301).redirect( your auth url );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM