如何调用express触发外部重定向并避免COR

时间:2019-08-26 14:59:46

标签: node.js ajax express cors shopify

我试图通过ajax调用从前端触发express.js路由。一旦路由被调用,它将重定向到外部重定向到另一个域。每次运行此路线时,都会遇到CORs飞行前错误。

我认为理想的工作流程应如下所示:

  1. 用户单击订阅按钮。
  2. 将AJAX(Jquery)调用发送到快速路由(app.get('/ shopify / new-charge'))。
  3. 特快路线开通。
  4. 触发外部重定向,并将用户发送到另一个域。

通过研究,我认为问题在于响应从后端返回前端。

我尝试实现以下内容:

  • 修改AJAX调用
  • server.js中的npm CORS
  • 将标头添加到server.js
  • 将标题添加到ajax
  • 将标题添加到重定向
  • 为重定向添加状态(res.redirect(301,'https://external-url.com')
  • 在res.redirect()之后添加next()
  • 将起点和起点与路线列入白名单

但是,我通过用表单包装按钮并消除了AJAX调用来成功解决了此冲突,但是我想知道是否可以通过前端的AJAX调用来实现。

前端Ajax呼叫

    activateSubscriptionButton.addEventListener('click', function () {
​
        var newChargeUrl = "/shopify/new-charge;
​
        $.ajax({
            type: "GET",
            url: newChargeUrl,
            data: {"shop" : test.com},
            success: function (result) {
                console.log('Success - Paid');
            },
            error: function (jqXHR, exception) {
                console.log('Error - No Paid');
                console.log('jqXHR :', jqXHR);
            },
        });
​
    }, false);

Express.js路线

app.get("/shopify/new-charge", function (req, res, next) {
            const shop_domain = req.query.shop;

            const shopRequestUrl = 'https://' + shop_domain + '/admin/api/2019-04/recurring_application_charges.json';

            const newCharge = {
                "recurring_application_charge": {
                    "name": "Professional Plan",//
                    "price": 4.99,
                    "return_url": forwardingAddress + "\/shopify\/billing\/activate?shop=" + encodeURIComponent(shop_domain),
                    "test": true,
                }
            };
                    request.post(shopRequestUrl,
                        {
                            headers: {
                                'X-Shopify-Access-Token': access_token,
                            },
                            json: newCharge
                        }, function (error, response, body) {
                            if (error) {
                                console.error('Error has occurred with charge: ', error);
                                return
                            }
                            else {
                                // Redirect User To External Confirmation Page//
                                res.redirect('https://external-url.com/');
                            }
                        })   
            else {
                res.send('Error: No shop_domain.');
            }
        });

Server.js

        var express = require("express");
        var app = express();
        var bodyParser = require("body-parser");
        const forwardingAddress = process.env.ngrok_forwarding_address;

        app.use(express.static("public"));
        app.use(bodyParser.urlencoded({ extended: true }));
        app.use(bodyParser.json());
        app.use(bodyParser.text());

        require("./controllers/shopify")(app);
        require("./controllers/billing")(app);

        // Setting up port and requiring models for syncing
        var PORT = process.env.PORT || 3000;

        app.listen(PORT, function () {
            console.log("Server listening on: http://localhost:" + PORT);
        });

以下是我运行上述代码时收到的错误:

选项:https://external-url.com 404

从原点“ https://external-url.com”到“ https://local.ngrok.com/shopify/new-charge?shop=test.com”(重定向自“ https://local.ngrok.com”)对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow_Origin”标头。

是否可以通过修改上面介绍的现有代码来实现我的目标?

1 个答案:

答案 0 :(得分:0)

您真的错过了Shopify的基本功能。关于您的应用程序,请在您的合作伙伴帐户中进入您的应用程序设置,并为该应用程序创建一个应用程序代理调用。然后,您创建的端点就是您使用JS代码从前端调用的端点。 Shopify确保安全性,所有您的CORS问题都消除了。这就是存在应用程序代理的原因,以允许安全地对后端应用程序进行前端调用。

TL:DR;您的前端模式注定要失败,您应该重构以使用安全的App Proxy。