【问题标题】:how to make Nodejs redirect work when called via Vuejs通过Vuejs调用时如何使Nodejs重定向工作
【发布时间】:2019-01-26 00:14:46
【问题描述】:

我已经在 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默认是:

服务器{ 字符集 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 调用表单,然后再次返回应用程序的主页。

欢迎提出任何想法!

【问题讨论】:

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


    【解决方案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

    【讨论】:

    • 谢谢你,我会尽快再次访问代码。
    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2018-09-15
    • 2018-12-01
    • 2015-08-02
    • 1970-01-01
    • 2020-01-11
    相关资源
    最近更新 更多