如何从feathers.js 服务重定向

Ale*_*aru 4 node.js feathersjs

我有一个feathers.js 服务,我需要在使用post 时重定向到特定页面

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

      return res.redirect('http://some-page.com');
   }
}
Run Code Online (Sandbox Code Playgroud)

是否可以从feathers.js 服务重定向?

Der*_*nel 5

我不确定这对于羽毛来说是一个多么好的实践,但是您可以res在羽毛上粘贴对对象的引用params,然后按照您的意愿进行处理。

// 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();
});
Run Code Online (Sandbox Code Playgroud)

然后在你的班级:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*aru 5

找到了一种更友好的方式来做到这一点:

假设我们有一个自定义服务:

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');
}
Run Code Online (Sandbox Code Playgroud)

背后的想法是feathers.js使用 express 中间件,逻辑如下。

如果链接的中间件是Object,则在您可以链接任意数量的中间件之后,将其解析为服务。

app.use('api/v1/messages', middleware1, feathersService, middleware2)
Run Code Online (Sandbox Code Playgroud)