Node.js Web服务是什么样的?

Mat*_*ere 7 javascript web-services node.js

我正在研究Node.js并考虑使用它来构建API.据我所知,ExpressJS将是Web框架,而不是我想要解决的问题.

那么Web服务会是什么样子?它只是创建一个服务器,与mongo交谈并返回结果?此外,路由是什么样的?(我显然想'设计'路线).

小智 4

如果 Express 将成为您的 Web 框架,请查看用于路由 API 的express-resource (Github) 中间件。您定义资源,它会用很少的样板为您连接 REST 风格的路由。

app.resource('horses', require('./routes/horses'), { format: json })
Run Code Online (Sandbox Code Playgroud)

鉴于上述情况,express-resource 会将所有 REST 风格的路由连接到您提供的操作,默认返回 JSON。在 中routes/horses.js,您可以按照以下方式导出该资源的操作:

exports.index = function index (req, res) {
  // GET http://yourdomain.com/horses
  res.send( MyHorseModel.getAll() )
}

exports.show = function show (req, res) {
  // GET http://yourdomain.com/horses/seabiscuit
  res.send( MyHorseModel.get(req.params.horse) )
}

exports.create = function create (req, res) {
  // PUT http://yourdomain.com/horses
  if (app.user.canWrite) {
    MyHorseModel.put(req.body, function (ok) { res.send(ok) })
  }
}

// ... etc
Run Code Online (Sandbox Code Playgroud)

您可以用不同的表示来回应:

exports.show = {
  json: function (req, res) { 
    // GET http://yourdomain/horses/seabiscuit.json
  }
, xml: function (req, res) {
    // GET http://yourdomain/horses/seabiscuit.xml
  }
}
Run Code Online (Sandbox Code Playgroud)

像express-resource这样的中间件可以让Node和Express的使用变得更加容易,查看github上的示例,看看它是否能满足您的需要。