Node Programming (iii)--building node Web program 1

Source: Internet
Author: User
Tags javascript array

First, the basic knowledge of HTTP server

1. How node renders HTTP requests to developers

The HTTP module in node provides the HTTP server and Client interface:

var http = require (' http ');

  Create an HTTP server to invoke the Http.createserver () function. It has only one function, which is a callback function that is called by the server each time it receives an HTTP request. This request callback receives two parameters, the request and response objects, usually abbreviated to req and res.

var http = require (' http '); var server = Http.createserver (function(req,res) {    // processing Request });

  2. An HTTP server that responds with "Hello World"

var http = require (' http '); var server = Http.createserver (function(req,res) {    res.end (' Hello World ');}); Server.listen (3000);

 3. Read the request header and set the response head

Node provides several ways to modify HTTP responses: RES.SETHEADRT (field.value), Res.getheader (field), and Res.removeheader (field).

  The order in which the response headers are added and removed can be arbitrary, but be sure to call Res.write () or Res.edn () before. After the first part of the response body is written, node refreshes the already set HTTP header

4. Set the status of the HTTP response

We often want to return HTTP status codes other than the default state 200.

II. Building RESTful Web Services

This section creates a RESTful Web service, a service that uses HTTP method predicates to provide a thin API.

Creating a standard rest server requires implementing four HTTP verbs, each of which is an action task that overrides a to-do list:

POST add items to the to-do list

GET Displays the current list of items, or displays the details of a particular item.

DELETE removes items from the to-do list

PUT modifies an existing item.

1. Create a resource with a POST request.

According to restful parlance, the creation of a resource is usually corresponding to the predicate post, so post will create a matter in the to-do list.

In node, you can see which HTTP method (predicate) is used by checking the Req.method property. Knowing which method to use for the request, the server can know which task to perform.

When the HTTP parser of node reads in and parses the request data, he will make the data in the form of a data time, then parse the good chunks into it, waiting for the program to process.

We create a new Todo.js file

/** * POST request string Cache*/varHTTP = require (' http ');varurl = require (' URL '));varitems = [];//storing data in a regular JavaScript arrayvarServer = Http.createserver (function(req,res) {Switch(Req.method) {//Req.method is to request all HTTP methods         Case' POST ':            varitem = ';//set the character cache for incoming thingsReq.setencoding (' UTF8 ');//encodes the incoming data event into a UTP-8 stringReq.on (' Data ',function(chunk) {Item+ = chunk;//bring data to the cache            }); Req.on (' End ',function() {Items.push (item); //Press the complete new item into the event arrayRes.end (' ok\n ');            });  Break; }});

2. Get resources with GET requests

To handle get, I'm adding him to the switch language, plus the logic of the To-dos

varHTTP = require (' http ');varurl = require (' URL '));varitems = [];//storing data in a regular JavaScript arrayvarServer = Http.createserver (function(req,res) {Switch(Req.method) {//Req.method is to request all HTTP methods         Case' POST ':            varitem = ';//set the character cache for incoming thingsReq.setencoding (' UTF8 ');//encodes the incoming data event into a UTP-8 stringReq.on (' Data ',function(chunk) {Item+ = chunk;//bring data to the cache            }); Req.on (' End ',function() {Items.push (item); //Press the complete new item into the event arrayRes.end (' ok\n ');            });  Break;  Case' GET ': Items.foreach (function(item,i) {res.write (i+ ') ' +itme+ ' \ n ');            });            Res.end ();  Break; }});

  node, like other languages, provides a repl (read-compute-output-loop) environment, which runs node without any parameters on the command line to enter the environment.

3. Remove Resources with delete request

......    Case' DELETE ':            varPath =Url.parse (req.url). Pathname; vari = parseint (Path.slice (1), 10); if(IsNaN) {//Check that the numbers are validRes.statuscode = 400; Res.end (' Invalid item ID '); }Else if(!item[i]) {//ensure that the requested index existsRes.statuscode = 404; Res.end (' Item not found '); }Else{Itmes.splice (i,1);//Delete Request ItemRes.end (' ok\n '); }             Break;

Node Programming (iii)--building node Web program 1

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.