Search code examples
javascriptexpressloopbackjsloopback

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

Solution

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