首页 > 解决方案 > 如何通过 axios 的请求在 2 中传递最终响应

问题描述

用户向服务器 1 发出 http 请求并传递一个 json 文件。-> 然后,服务器 1 使用 json 文件向服务器 2 运行 http 请求(同时向用户 200/超时等发送响应......) -> 服务器 2 返回值 -> 值返回给服务器 1... 问题是:如何将值传递给用户?

我找不到传递最终值的方法。

用户到服务器 1:

axios({
       method: 'post',
       url: Url,
       headers: {
       "Content-Type": "application/json"
       },
       timeout: 30000, // Wait for 30 seconds
       data: data
       }).then(function(response){
       console.log(response)
       }).catch(function(error) {
       console.log(error)
      })

服务器 1 到服务器 2:

app.use('/payment', (req, res)=> {
      var data = req.body
      data.CreditboxToken = creditToken
      axios({
            method: 'post',
            url: urlPayment,
            headers: {
              "Content-Type": "application/json"
            },
            timeout: 30000, // Wait for 30 seconds
            data: data
          })
          .then(function(response){
            console.log(response.data)
            res.send(response.data)
          })
          .catch(function(error) {
            console.log(error)
          });
})

标签: javascriptnode.jsexpressaxios

解决方案


您在示例中的内容看起来像是一种可行的方法。服务器 1 上的 axios 调用创建并执行对服务器 2 的调用,只有当服务器 2 成功时,它才会向用户执行“res.send”。

你没有提到你在这里看到的实际行为,你的 console.logs 输出什么?

注意:如果用户对 server1 的 http 请求已经完成(即 server1 响应或连接超时),则该特定请求的上下文将关闭并完成。然后,如果没有其他请求,您就无法将服务器 2 的响应返回给用户。


推荐阅读