简体   繁体   English

我应该如何在Node.js中使用Web前端实现RESTful API?

[英]How should I implement a RESTful API with a web frontend in Node.js?

I have a setup consisting of multiple servers (written in Java) that need to communicate towards a central server, posting status updates every so often. 我有一个由多个服务器(用Java编写)组成的设置,需要与中央服务器通信,每隔一段时间发布一次状态更新。 These status updates will get written to a database, probably MongoDB/Mongoose which will be handled by the web end via REST. 这些状态更新将被写入数据库,可能是MongoDB / Mongoose,它将由Web端通过REST处理。

I have been looking at Restify and Express as two ways to approach this problem. 我一直在寻找Restify和Express作为解决这个问题的两种方法。 The website will query the database as well as the REST api. 该网站将查询数据库以及REST api。

How should I approach this? 我该怎么做呢? Should I use both Restify and Express to create a website with an API? 我应该使用Restify和Express来创建一个带有API的网站吗? Should I use Railway? 我应该用铁路吗? Thanks. 谢谢。

It doesn't make sense to use a complex framework such as Railway, which is built on top of Express and tries to resemble Ruby on Rails. 使用像铁路这样的复杂框架是没有意义的,它构建在Express之上,并试图类似于Ruby on Rails。

You should either choose Express or Restify, not both. 你应该选择Express或Restify,而不是两者。

I would pick Express over Restify because the code is excellently documented and the library is more mature and heavily used. 我会选择Express over Restify,因为代码记录很好,而且库更成熟,使用频繁。 You can find a bunch of useful tutorials on how to make such apps with Express, and the API is great: 你可以找到一些有关如何使用Express制作此类应用程序的有用教程,API非常棒:

var express = require('express')
  , app = express.createServer();

var users = [{ name: 'tj' }];

app.all('/user/:id/:op?', function(req, res, next){
  req.user = users[req.params.id];
  if (req.user) {
    next();
  } else {
    next(new Error('cannot find user ' + req.params.id));
  }
});

app.get('/user/:id', function(req, res){
  res.send('viewing ' + req.user.name);
});

app.get('/user/:id/edit', function(req, res){
  res.send('editing ' + req.user.name);
});

app.put('/user/:id', function(req, res){
  res.send('updating ' + req.user.name);
});

app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000); 

I personally find express.js to suit my needs because of it's routing functionality that is great. 我个人觉得express.js能够满足我的需求,因为它的路由功能很棒。 Check out http://expressjs.com/guide.html#routing . 查看http://expressjs.com/guide.html#routing It gets the job done for a RESTful api and is extremely fast. 它完成了RESTful api的工作并且非常快。

also: Node-PerfectAPI vs Restify.js vs ExpressJS vs Node-APIServer 另外: Node-PerfectAPI vs Restify.js vs ExpressJS vs Node-APIServer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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