首页 文章

如何通过Vuejs调用Nodejs重定向工作

提问于
浏览
1

我在Nodejs中创建并测试了POST和GET请求方法,这样我就可以完全通过Gocardless注册API发送给用户 .

这是他们的API提供的注册表单,允许他们输入他们的详细信息,然后在用户填写后返回用户 .

但是,当我使用Vuejs设置前端并使用Axios进行之前使用后端进行的相同调用时,似乎因为从GC API反馈给我的“redirect_url”之前已直接输入到浏览器URL中之前,现在,因为似乎vue-router控制了浏览器,我得到了一个跨源错误 .

如何配置文件以使Nodejs后端的操作就像控制浏览器一样?

终点如下所述:https://developer.gocardless.com/api-reference/#core-endpoints-redirect-flows

我的nginx默认是:

服务器{charset UTF-8;

listen 80;

 root /srv/www/sitename/;
 index index.html;
 server_name sitename.com;

  location /api/ {
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_http_version 1.1;
     proxy_set_header X-NginX-Proxy true;
     proxy_pass http://sitename.com:8081;
     proxy_ssl_session_reuse off;
     proxy_set_header Host $http_host;
     proxy_redirect off;
  }
  location / {
     try_files $uri.html $uri $uri/ /index.html;
    }

来自Vuejs前端的按钮:

completeOrder()

..并以这种方式使用axios:

import axios from 'axios'

export default() => {
  return axios.create({
    baseURL: 'http://sitename.com:8081/api'
  })
}

并在此处设置:

import Api from '@/services/Api'

    export default {
      completeOrder () {
        return Api().post('order')
      }
    }

在后端,它发送:

app.post('/api/order', function (req, res){
        rp({              
          //rp is npm request-promise
          uri: BASE_URL + "/redirect_flows",
          method: 'POST',
          body:JSON.stringify(input_json),
          headers: headers
        })  // this works and API sends me the response
        .then(function(response) {
          var str_response =JSON.parse(response);
          url = str_response['redirect_flows']['redirect_url']  
          // url works fine when I paste into a separate browser
          res.redirect(url)
    })
    .catch(function (err) {
        console.error(err);
    })
})

一切正常,直到这一点:

res.redirect(url)

.. Gocardless API响应提供了我需要加载到浏览器中的URL .

它看起来像这样:

https://pay-sandbox.gocardless.com/flow/RE000156

我想我需要通过vue-router打破Vuejs对浏览器的控制,只需足够长的时间允许用户使用redirect_url调用表单,然后再次返回应用程序的主页 .

任何想法都非常欢迎!

1 回答

  • 1

    我认为你实际上有一个JS错误 . 在 then 块中实例化 response ,但是使用 res 变量进行重定向 . 尝试查找变量

    .then(function(response) {
          var str_response = JSON.parse(response);
          url = str_response['redirect_flows']['redirect_url']  
          // url works fine when I paste into a separate browser
          response.redirect(url)
    })
    

    我不是Vue.JS专家,所以我不知道是否可行,请尝试使用vanilla JS重定向来测试此功能:

    window.location.href = url;
    

    这样,您将确保该网址有效 . 之后,尝试checking out a full Vue.JS option .

相关问题