Jornve
Jornve

Reputation: 299

Loopback / Express: How to redirect to URL inside a remoteMethod?

I am having a hard time finding any documentation regarding redirecting to a URL inside a model function or remoteMethod. Has anyone here already done this? Please find my code below.

Function inside Model (Exposes /catch endpoint)

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

Upvotes: 3

Views: 3598

Answers (2)

Iwan Bhakti S
Iwan Bhakti S

Reputation: 31

You can get response object from HTTP context, then inject it as a parameter into remote method, and use it directly:

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

Upvotes: 3

Denis Wells
Denis Wells

Reputation: 115

I found an answer here. You need to create a remote hook and access the res Express object. From there, you can use res.redirect('some url').

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

Upvotes: 7

Related Questions