【问题标题】:Loopback / Express: How to redirect to URL inside a remoteMethod?Loopback / Express:如何重定向到远程方法中的 URL?
【发布时间】:2018-04-04 03:46:33
【问题描述】:

我很难找到有关重定向到模型函数内的 URL 或 remoteMethod 的任何文档。这里有人已经这样做了吗?请在下面找到我的代码。

模型内部的函数(暴露 /catch 端点)

Form.catch = function (id, data, cb) {
    Form.findById(id, function (err, form) {

      if (form) {
        form.formentries.create({"input": data},
          function(err, result) {
            /*
             Below i want the callback to redirect to a url  
             */
            cb(null, "http://google.be");
          });
      } else {
        /*
         console.log(err);
         */
        let error = new Error();
        error.message = 'Form not found';
        error.statusCode = 404;
        cb(error);
      }
    });
    };

    Form.remoteMethod('catch', {
    http: {path: '/catch/:id', verb: 'post'},
    description: "Public endpoint to create form entries",
    accepts: [
      {arg: 'id', type: 'string', http: {source: 'path'}},
      {arg: 'formData', type: 'object', http: {source: 'body'}},
    ],
    returns: {arg: 'Result', type: 'object'}
    });

【问题讨论】:

    标签: javascript express loopbackjs loopback


    【解决方案1】:

    我在这里找到了answer。您需要创建一个remote hook 并访问res Express 对象。从那里,您可以使用res.redirect('some url')

    Form.afterRemote('catch', (context, remoteMethodOutput, next) => {
      let res = context.res;
      res.redirect('http://google.be');
    });
    

    【讨论】:

      【解决方案2】:

      您可以从 HTTP 上下文中获取响应对象,然后将其作为参数注入到远程方法中,并直接使用它:

      Model.remoteMethodName = function (data, res, next) {
          res.redirect('https://host.name.com/path?data=${data}')
      };
      
      Model.remoteMethod('remoteMethodName', {
          http: {
              path: '/route',
              verb: 'get',
          },
          accepts: [
              {arg: 'data', type: 'string', required: false, http: {source: 'query'}},
              {arg: 'res', type: 'object', http: ctx => { return ctx.res; }},
          ],
          returns: [
              {arg: 'result', type: 'any'}
          ],
      });
      

      【讨论】:

      • 感谢@Iwan Bhakti S,这种方法更好,因为它避免 express.js 抱怨 http 标头,这可能在我们实际到达 .afterRemote 代码之前已经发送
      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      相关资源
      最近更新 更多