Loopback / Express:如何重定向到remoteMethod中的URL?

时间:2017-10-23 14:34:01

标签: javascript express loopbackjs loopback

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

模型内的功能(Exposes / 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'}
    });

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

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'}
    ],
});