Using node JS to quickly simulate the web API

Source: Internet
Author: User

Label:

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:

焦点图/sample_app/focus_pic文章列表/sample_app/article_list文章详情/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 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. */// 针对不同的请求,做出不同的相应function route(handler, parsedUrl, request, response) {    var pathname = parsedUrl.pathname;    console.log(‘About to route a request for ‘ + pathname);    // 禁止访问favicon.ico    if (!pathname.indexOf(‘/favicon.ico‘)) {        return;    }    // 这里不用检查请求路径是否正确,将路由放到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

/** * 请求处理入口。 */function handleRequests(parsedUrl, request, response) {    // 解码并解析querystring    //var queryStringUtil = require(‘querystring‘);    //var queryString = parsedUrl.query;    //var queryStringResultObject = queryStringUtil.parse(queryString);    var pathname = parsedUrl.pathname;    // 在这里进行处理}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, +, ' 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 named appProperties.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 variable var routeObj; first
This is then handled in the function handleRequests :

//Parse route configuration information    if(!routeobj) {varFS =require(' FS ');varPropertiespath ='./appproperties.json ';varPropertiesdata = Fs.readfilesync (Propertiespath,' Utf-8 '); Routeobj =JSON. Parse (Propertiesdata); }varTemplateobj = routeobj[' Route '][pathname];if(templateobj) {handlevalidrequest (Request, Response, templateobj[' template '], templateobj[' inner_html ']); }Else{Handleerroroutput (Request, Response, -,' 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 one else 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.

Tags Index: