node.js - 从featherJS应用程序调用远程休息服务的最佳实践

标签 node.js node-request feathersjs

我需要一种从 FeatherJS(基于 Express 的 NodeJS 框架)应用程序调用远程 REST-API 的方法。

我发现了几篇建议使用请求模块的帖子,这很好:https://github.com/request/request

既然我正在使用 FeatherJS,还有什么更好的建议吗?或者请求模块就可以了吗?

最佳答案

我推荐使用 request-promise 模块,因为 Feathers 服务需要 Promise。这是一个示例服务 from this post how to make an existing API real-time :

const feathers = require('feathers');
const rest = require('feathers-rest');
const socketio = require('feathers-socketio');
const bodyParser = require('body-parser');
const handler = require('feathers-errors/handler');
const request = require('request-promise');

// A request instance that talks to the API
const makeRequest = request.defaults({
  baseUrl: 'https://todo-backend-rails.herokuapp.com',
  json: true
});

const todoService = {
  find(params) {
    return makeRequest(`/`);
  },

  get(id, params) {
    return makeRequest(`/${id}`);
  },

  create(data, params) {
    return makeRequest({
      uri: `/`,
      method: 'POST',
      body: data
    });
  },

  update(id, data, params) {
    // PATCH and update work the same here
    return this.update(id, data, params);
  },

  patch(id, data, params) {
    return makeRequest({
      uri: `/${id}`,
      method: 'PATCH',
      body: data
    });
  },

  remove(id, params) {
    // Retrieve the original Todo first so we can return it
    // The API only sends an empty body
    return this.get(id, params).then(todo => makeRequest({
      method: 'DELETE',
      uri: `/${id}`
    }).then(() => todo));
  }
};

// A normal Feathers application setup
const app = feathers()
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(rest())
  .configure(socketio())
  .use('/todos', todoService)
  .use('/', feathers.static(__dirname))
  .use(handler());

app.listen(3030);

关于node.js - 从featherJS应用程序调用远程休息服务的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894292/

相关文章:

node.js - 403 禁止 - 使用 Passport.io + express + socket.io 跨子域的 socket.io 连接

node.js - Twilio session 语音邮件/机器检测

javascript - 使用 Nodejs 请求模块对返回未定义进行地理编码的函数

node.js - 类型脚本路径不起作用。即使在 tsconfig.json 中设置了 "baseUrl"属性之后

javascript - 如何使我的 Node.js websocket socket.io 服务器对 DoS 更具弹性?

node.js - Webpack2 热模块重新加载 Express.js 通用 React 应用程序

node.js - 来 self 们当前 SailsJS 服务器的统计数据

node.js - 如何从请求模块响应中存储cookie客户端

feathersjs - 使用feathers-client并续集多对多关系

sequelize.js - Feathers-Sequelize:hasMany 只返回第一个结果,展平