简体   繁体   中英

How to redirect from a feathers.js service

I have a feathers.js service and I need to redirect to a specific page when using post

class Payment {
   // ..
   create(data, params) {
      // do some logic
      // redirect to an other page with 301|302

      return res.redirect('http://some-page.com');
   }
}

Is there a posibility to redirect from a feathers.js service ?

Found a way to do this in a more friendly manner:

Assuming we have a custom service:

app.use('api/v1/messages', {
  async create(data, params) {
    // do your logic

    return // promise
  }
}, redirect);

function redirect(req, res, next) {
  return res.redirect(301, 'http://some-page.com');
}

The idea behind is that feathers.js use express middlewares and the logic is the following one.

If the chained middleware is an Object , then it is parsed as a service, after you can chain any number of middlewares you want.

app.use('api/v1/messages', middleware1, feathersService, middleware2)

I'm not sure how much of a good practice in feathers this would be, but you could stick a reference to the res object on feathers' params , then do with it as you please.

// declare this before your services
app.use((req, res, next) => {
    // anything you put on 'req.feathers' will later be on 'params'
    req.feathers.res = res;

    next();
});

Then in your class:

class Payment {
    // ..
    create(data, params) {
    // do some logic
    // redirect to an other page with 301|302
    params.res.redirect('http://some-page.com');

    // You must return a promise from service methods (or make this function async)
    return Promise.resolve();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM