简体   繁体   中英

Resource based routing module used in a Node.js REST API service, or other useful modules for this type of service

We are building a service that exposes a REST Api to the clients and we are using jugglingdb to create the models and express as the server.. I was wondering if there are any modules that are useful when creating a RESTful API in node.js

I tried using restify but it seemed to be just a watered down version of express and seemed to lack some functionality i needed from express, so i switched to express.

EDIT: We have no front-end. So we are strictly a rest api service that just provides data for various clients

RESTfull API get and post data through HTTP protocol. A more progressive approach is to use WebSocket [Wikipedia] npm link . Try to play with Sails.js framework build on Express.js that use Socket.IO for flash data transfering

One approach to consider is to keep things light and simple. If you don't have a front end, you can use the Connect module alone instead of Express, which is built on Connect:

http://www.senchalabs.org/connect/

I had good luck with this approach with my Node.js RESTful API. I did end up with a few repeated patters, especially in parsing incoming post data at times. But I found the code snips were just too small to be worth putting into a module, and it offered me amazing flexibility in certain situations.

One more approach that worked very well for me: Post ALL of your data as JSON - not as post key/value pairs. Depending on your API's clients, you may be able to do this. My API client was jQuery AJAX calls from a web page. It's very easy to send a JSON post. The jQuery processData property allows this as follows:

    $.ajax({
        url: '/nodeAjaxHandler',
        type: 'POST',
        data: JSON.stringify(formVals),
        processData: false,
        dataType: 'json',
        success: function(data) {
        },
        error: function(a, b, c) {
        }
    });

Now receiving the data in your Node server is as simple as waiting for the body text to load, then JSON.parse it into an object. Very readable and manageable. And when you change the data fields being posted and received, you don't need to change any of the interface code at all!

(And you can go one step further if you dare, and make the field names match your database field names - then you can consolidate even more code. This felt risky to me but worked brilliantly - I'm not sure what the down sides might be yet. I do escape all my field names as well as my column names in the mySQL queries.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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