[NodeJS] Node Development Web program Getting Started

Source: Internet
Author: User

Node built-in HTTP module provides HTTP server and client interface

var http = require ("http");

To create an HTTP server, simply call the Http.createserver () function, the parameter is a callback function, and receive two parameters: request, Response object.

var server = Http.createserver (function (req, res) {});

The HTTP request header was parsed by node before the callback function was triggered, but the request body was not parsed. There is also a need for developers to call the Response.End () method to end the response.

The HTTP server needs to bind a port number to listen for incoming requests. Using the Listen method of the Http.server class

One of the simplest HTTP server code:

var http = require ("http"); var server = Http.createserver (function(req, res) {    res.write ("Hello World");    Res.end ();} Server.listen (8080);

Next, let's look at how to get the request header information and how to set the response header information

1. Get Request header information

Req.headers

Req.rawheaders

The request header information is obtained through these two properties. The difference between the two is that headers gets the object that is the key-value pair format, and the duplicate request header information is discarded. The rawheaders gets a list, an odd number is the request header name, even the request header information, and the duplicate request header information is also placed in the list.

2. Setting the response header information

The Response object provides SetHeader (field, value), GetHeader (field, value), Removeheader (field) method

Set the response header before sending the message body, the usual response headers include

Content-type: "Text/plain", "text/html"

Content-length setting the byte length of the response message body you can use the Buffer.bytelength method to get the actual byte length of the string data

3. Set the response status code

Response.statuscode

The HTTP module in Nodejs provides the Http.status_codes attribute to describe the status code and description of the standard HTTP protocol specification

Setting Response.statuscode = 302 indicates redirection

Building RESTful Web Services

Creating a standard Rest server requires four HTTP operations: the POST GET DELETE PUT corresponds to what people often call curd operations

In addition people often use the Curl command line to do web operations

When there is a request to send the data, the HTTP parser will make the data event form, the parsed data into the chunk. The data event and end event that listens for request requests

var http = require ("http"); var server = Http.createserver (function(req, res) {    req.setencoding ("Utf-8");    Req.on (function(chunk) {        Console.log ("parsed", chunk);    });    Req.on (function() {        console.log ("done parsing");        Res.end ();    } );

Use the Req.method property to determine how the request is requested

Parsing URL path Information also requires a core module URL

By understanding the Req.method,url, and the data parsing principle of the Request object, it is beneficial to use the encapsulated high-level framework later.

For example, in Express, you provide. All (). get (). Post (). put (). Delete () method

Building a static file server

The Stream.pipe () method can be understood as the flow of source data (Readablestream) through a piping pipe to a destination (Writablestream)

All Readablestream can be connected to any writeablestream, such as request is a readablestream, response is a writablestream

varHTTP = require ("http");varParse = require ("url"). Parse;varJoin = require ("path"). Join;varFS = require ("FS");varRoot =__dirname;varServer = Http.createserver (function(req, res) {varpathname =Parse (req.url). Pathname; varPath =Join (root, pathname); Fs.stat (Path,function(err, stat) {if(err) {if(Err.code = = = "ENOENT") {Res.statuscode= 404; Res.end ("Not Found"); }Else{Res.statuscode= 500; Res.end ("Internal Server Error"); }        }Else{            //no errors, ready to read the contents of the file and returnRes.setheader ("Content-length", stat.size); varstream =fs.createreadstream (path);            Stream.pipe (RES); Stream.on ("Error",function(Err) {Res.statuscode= 500; Res.end ("Internal Server Error");        }); }    });}); Server.listen (8080);

[NodeJS] Node Development Web program Getting Started

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.