What does the Node.js web service look like?

I am considering Node.js and thinking about using it to create an API. From what I can say, ExpressJS will be a web framework and is not what I would like to solve.

So what would a web service look like? Will it just be creating a server, communicating with mongo and returning results? Also, what does routing look like? (I would obviously like to β€œdevelop” the routes).

+7
source share
3 answers

If Express will be your web framework, look at the express-resource (Github) API routing middleware. You define resources and include a REST style for you with a very small template.

app.resource('horses', require('./routes/horses'), { format: json }) 

Given the above, express-resource will connect all REST-style routes to your actions, returning JSON by default. In routes/horses.js you export the actions for this resource according to:

 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 

You can respond with different views:

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

Middlewares such as express-resource can make life easier with Node and Express, check out the github examples to see if it does what you need.

+4
source

Here is a stub that looks for the horse name from the Postgres database and returns the result as JSON. Clients will gain access to the API by going to http://yourdomain.com/api/horse/seabiscuit

 app.get('/api/horse/:name', function(req, res){ pg.connect(conString, function(err, client) { var horse = req.params.name; var sql = "..."; client.query(sql, function(err, result) { if (err) { ... } for (var i=0; i<result.rows.length; i++) { // Customize data as needed } return res.send(JSON.stringify(result.rows)); }); }); }); 
+2
source

Node is pretty low. This is similar to C in JavaScript clothes. Since this is comparable to C, you can do a lot with Node. Creating web servers is just one of them. You can create chat servers using sockets, blogs, streaming, etc. The possibilities are endless. You are limited only by your imagination.

Routing is simply a task in which you accept commands (usually through URLs or headers) and perform tasks based on these commands.

But even I haven't rocked the Node surface yet. It has a huge API and is getting bigger. Better try using some basic library, such as Express or Connect, as they quite abstractly outline the basic requirements for creating a server from code.

+1
source

All Articles