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

时间:2018-08-19 19:17:36

标签: node.js api nginx vue.js axios

我已经在Node.js中创建并测试了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默认值为:

服务器{      字符集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 个答案:

答案 0 :(得分: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专家,所以我不知道这是否可行,请尝试使用普通JS重定向来测试此功能:

window.location.href = url;

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