Using node JS to quickly simulate the web API

Source: Internet
Author: User
Tags object serialization



The Web API is not associated with a specific programming language, even if the API interface is invoked over the network. It is now common to get a response from the server through a standard HTTP Get/post request, a resource or service that returns the resulting content of the call, typically in XML format or JSON format (more now using JSON).



When developing an app, the generic prototype is well designed (such as using tools such as just in mind), and we design an interface document that interacts with the server. In general, app development progress (especially prototyping) is faster than server development. During the application static prototype development to the server implementation of all the interactive interface during this period, we certainly can not idle. At this point, we can simulate an HTTP server locally to continue the app's "dynamic" development.



Because of the familiarity with JavaScript, after a simple look at node JS, it is used to develop the local HTTP server and provide a variety of interactive interface. Here is a record of how the step-by-step implementation.


Step-by-step implementation of an HTTP server


For example, 3 interfaces are fabricated (regardless of how many, the principle is the same), as follows:


Focus map
/sample_app/focus_pic

Article list
/sample_app/article_list

Article details
/sample_app/article_detail


We can divide the server into the following modules:


    1. Portal-App.js, the overall Management server. Typically starts the server
    2. Server module-Server.js, which is responsible for server configuration and forwarding of requests. such as the server listening port, request log records, request forwarding to the specific processing function, etc.
    3. Router module-Router.js, as the name implies, is responsible for the routing function of the request. For example, here we can forward different request addresses to different function processing.
    4. Request handlers Module-Request_handler.js, the function that is processed for each request is defined inside the module.
    5. Response Template module, since we just quickly simulate the HTTP server that provides the Web API service, the content that is actually returned is written inside the template.


In fact, the routing of the 3 interfaces (the different requests to the corresponding processing functions) should be handled in the router module, but because the processing logic for each interface is the same, but the content returned is different, I transfer the routing logic to the request handlers module. How to write, can be adjusted according to the actual situation, where the side just provides a way of thinking.



Look at the text is still more obscure, we look at the specific code:
Server.js


/**
  * Created by FIMH on 2016/05/05.
  */
Var http = require(‘http‘);
Var url = require(‘url‘);

Function start(route, handle) {
     Function onRequest(request, response) {
         / / Get the request path
         Var parsedUrl = url.parse(request.url);
         Var pathname = parsedUrl.pathname;

         Console.log(‘Request for ‘ + pathname + ‘ received.’);

         Route(handle, parsedUrl, request, response);
     }

     http.createServer(onRequest).listen(9999);
     Console.log(‘Server has started.‘);
}

Exports.start = start; 


As you can see, the main configuration is the HTTP server listening Port-9999, and print a log information, and then transfer the request to the router module for processing



Router.js


/**
  * Created by FIMH on 2016/05/05.
  */
// Make different responses for different requests
Function route(handler, parsedUrl, request, response) {
     Var pathname = parsedUrl.pathname;
     Console.log(‘About to route a request for ‘ + pathname);

     // prohibit access to favicon.ico
     If (!pathname.indexOf(‘/favicon.ico‘)) {
         Return;
     }

     // There is no need to check if the request path is correct, and put the route into the function corresponding to the handle.
     Handler(parsedUrl, request, response);
}

Exports.route = route; 


Here we mainly intercept the access to the Favicon.ico file, about what this file is, you can search by yourself.
As mentioned earlier, because this sample inside, the processing logic of each interface is the same, but the content of the return is different, I will transfer the routing logic to the request handlers module.



The real processing logic is in the following module
Requests_handlers.js


/**
  * Request processing entry.
  */
Function handleRequests(parsedUrl, request, response) {
     // Decode and parse the querystring
     //var queryStringUtil = require(‘querystring‘);
     //var queryString = parsedUrl.query;
     //var queryStringResultObject = queryStringUtil.parse(queryString);

     Var pathname = parsedUrl.pathname;

     // handle it here
}

exports.handleRequests = handleRequests; 


Here, I've only posted a request to handle the entry function.
In this place I refactored once, the initial processing logic is roughly as follows:


var templateName;
    var innerHtml; if (pathname == ‘/sample_app/focus_pic‘) {
       templateName = ‘focus_pic‘;
    } else if (pathname == ‘/sample_app/article_list‘) {
        templateName = ‘article_list‘;
    } else if (pathname == ‘/sample_app/article_detail‘) {
        templateName = ‘article_detail‘;
        innerHtml = ‘article‘;
    } if (templateName) {
        handleValidRequest(request, response, templateName, innerHtml);
    } else {
        handleErrorOutput(request, response, 400, ‘Invalid request url!‘);
    }


Because here is only 3 requests, look still not obvious, if more, then if...else write up is too annoying, this time I think of a lot of JS language projects (such as Cocos 2d-js,egret) will use the JSON file as the project's configuration file, in order to simplify the code and improve flexibility.



At this point, we can define a project configuration file, which I namedappProperties.json, the content is as follows


{
  "route": {
    "/sample_app/focus_pic": {
      "template": "focus_pic" },
    "/sample_app/article_list": {
      "template": "article_list" },
    "/sample_app/article_detail": {
      "template": "article_detail",
      "inner_html": "article" } } }


Then we modify the previously mentioned module-requests_handlers.js
Define a global variablevar routeObj;first
This is then handled in the functionhandleRequests:


/ / Parse the route configuration information
     If (!routeObj) {
         Var fs = require(‘fs‘);
         Var propertiesPath = ‘./appProperties.json‘;
         Var propertiesData = fs.readFileSync(propertiesPath, ‘utf-8‘);

         routeObj = JSON.parse(propertiesData);
     }

     Var templateObj = routeObj[‘route‘][pathname];
     If (templateObj) {
         handleValidRequest(request, response, templateObj[‘template‘], templateObj[‘inner_html‘]);
     } else {
         handleErrorOutput(request, response, 400, ‘Invalid request url!‘);
     } 


After refactoring, regardless of the number of interfaces, the code is still the lines of processing, and the method before refactoring, each adding an interface, need to add oneelse if.
The concept of algorithmic complexity is compared, the first is O (n), and the Reconstruction is O (1).



Regarding the processing of the Response template module, the code is not posted here. The main is to use node JS synchronous or asynchronous read template file, and JSON object serialization, editing and deserialization. If you are interested, you can see the source code of the whole sample, see the bottom of the article.


Summary and Source code


If you use the traditional way, you need to install an HTTP server-like Apache, and a language processing module-such as PHP.
After using node JS, you only need to install a node runtime, the remaining HTTP server, request parsing, processing, return and so on all use JS to write, and the amount of code written is also very small.



The code for the entire project I put on GitHub, see Nodejs_sample_app



Using node JS to quickly simulate the web API


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.