Node.js:get/post requests, global objects, tool modules

Source: Internet
Author: User
Tags event listener try catch to domain

First, get/post request

In many scenarios, our servers need to interact with the user's browser, such as form submissions. The get/post request is typically used by the form submission to the server.

1. Get GET Request Content

Because the GET request is embedded directly in the path, the URL is the complete request path, including the following section, so you can manually parse the following contents as parameters of the GET request. This function is provided by the parse function in the URL module in node. js.

varHTTP = require ('http');varurl = require ('URL');varUtil = require ('util'); Http.createserver (function (req, res) {Res.writehead ( $, {'Content-type':'Text/plain; Charset=utf-8'}); Res.end (Util.inspect (Url.parse (Req.url,true)));}). Listen ( the);

We can use the Url.parse method to parse the parameters in the URL

varHTTP = require ('http');varurl = require ('URL');varUtil = require ('util'); Http.createserver (function (req, res) {Res.writehead ( $, {'Content-type':'Text/plain'}); //Parsing URL Parameters    var params= Url.parse (Req.url,true). Query; Res.write ("Site Name:"+params. Name); Res.write ("\ n"); Res.write ("website URL:"+params. URL); Res.end (); }). Listen ( the);

2. Get POST Request Content

The contents of the POST request are all in the request body, HTTP. Serverrequest does not have a property content of the request body, because waiting for a request body transfer can be a time-consuming task. such as uploading files, and many times we may not need to ignore the content of the request body, malicious post requests will greatly consume the resources of the server, so node. js By default will not parse the request body, when you need to do it manually.

Basic syntax Structure Description:

varHTTP = require ('http');varQueryString = require ('QueryString'); Http.createserver (function (req, res) {//defines a post variable for staging the request body information    varPost ="'; //The data event listener function of req is added to the post variable whenever the request body is received .Req.on ('Data', function (chunk) {post+=Chunk;     }); //After the end event is triggered, the post is parsed into the true POST request format via Querystring.parse and then returned to the client. Req.on ('End', function () {post=Querystring.parse (POST);    Res.end (Util.inspect (POST)); });}). Listen ( the);

The following instance form submits and outputs data via POST

varHTTP = require ('http');varQueryString = require ('QueryString'); varposthtml =''+'<body>'+'<form method= "POST" >'+'site name: <input name= "name" ><br>'+'website URL: <input name= "url" ><br>'+'<input type= "Submit" >'+'</form>'+'</body>'; Http.createserver (function (req, res) {varBODY =""; Req.on ('Data', function (chunk) {body+=Chunk;  }); Req.on ('End', function () {//parsing ParametersBODY =Querystring.parse (body); //Setting the response header information and encodingRes.writehead ( $, {'Content-type':'text/html; Charset=utf8'}); if(Body.name && Body.url) {//output the submitted dataRes.write ("Site Name:"+body.name); Res.write ("<br>"); Res.write ("website URL:"+Body.url); } Else{//Output FormRes.write (posthtml);  } res.end (); });}). Listen ( the);
second, global objects

There is a special object in JavaScript called a global object, and all of its properties can be accessed anywhere in the program, that is, global variables.

In browser JavaScript, the window is usually a global object, while the global object in node . JS is global, and all global variables (except the global itself) are properties of the global object. In node. js, we can directly access the properties of global without having to include it in the app.

Global objects and global variables:

  The fundamental role of global is to be the host of variables . As defined by ECMAScript, variables that meet the following conditions are global variables:

    • Variables defined at the outermost layer;
    • The properties of the global object;
    • Implicitly-defined variables (variables that are not directly assigned) are defined.

When you define a global variable, the variable also becomes a property of the global object, and vice versa. It is important to note that in node. js You cannot define variables at the outermost layer because all user code belongs to the current module, and the module itself is not the outermost context.

Note: always use var to define variables to avoid introducing global variables, because global variables pollute namespaces and increase the risk of code coupling.

1.__filename represents the file name of the script that is currently executing. It will output the absolute path to the location of the file , and the file name specified with the command-line arguments is not necessarily the same. If the value returned in the module is the path to the module file.

// outputs the value of the global variable __filename Console.log (__filename); // Execute the Main.js file, as shown in the following code: $ node Main.js/web/com/nodejs/main.js

2.__dirname represents the directory where the script is currently executing. The above example, know the Nodejs directory

3,setTimeout (CB, MS) global function executes the specified function (CB) After the specified number of milliseconds (ms). : SetTimeout () executes the specified function only once. Returns a handle value representing the timer.

The cleartimeout (t) global function is used to stop a timer that was previously created by SetTimeout (). The parameter T is a timer created by the SetTimeout () function.

4,setinterval (CB, MS) global function executes the specified function (CB) After the specified number of milliseconds (ms). Returns a handle value representing the timer. You can use the clearinterval (t) function to clear the timer.

The SetInterval () method keeps calling functions until Clearinterval () is called or the window is closed.

5. Console is used to provide console standard output, which is a debugging tool provided by the JScript engine of Internet Explorer, and is gradually becoming the browser's implementation standard. node. JS uses this standard to provide a console object that is consistent with customary behavior to output characters to the standard output stream (STDOUT) or standard error stream (stderr).

console.time (label): output time, indicating the start of the timing.

console.timeend (label): end time, indicating that the timing is over.

console.trace (message[, ...]) : the current execution of the code in the stack of call path, this test function is very helpful, as long as you want to test the function inside the console.trace to join the line. debugging role

6, process is a global variable, that is, the properties of the global object.

It is used to describe the object of the current node. JS process State and provides a simple interface to the operating system. Usually when you write a local command-line program, you have to deal with it.

Three, tool module

There are many useful modules in the node. JS Module Library.

The OS module provides basic system operation functions. Some basic system operation functions are provided. We can introduce this module in the following ways:var os = require("OS")

The path module provides tools for processing and converting file paths. The path module provides a number of gadgets for working with file paths

NET module for the underlying network communication. Provides operations for both the server and the client. Provides a number of gadgets for the underlying network communication, including methods for creating a server/Client

The DNS module is used to resolve domain names.

The Domain module simplifies exception handling of asynchronous code and can catch exceptions that handle a try catch that cannot be caught.

Domain module, which handles multiple different IO operations as a group. Registering events and callbacks to domain, when an error event occurs or an error is thrown, the domain object is notified, does not lose the context, and does not cause the program error to exit immediately, unlike Process.on (' uncaughtexception ').

Domain modules can be divided into implicit and explicit bindings:

    • Implicit binding: Automatically binds a variable defined in the domain context to a domain object
    • Explicit binding: Binds a variable that is not defined in the domain context to a domain object in a code way

Node.js:get/post requests, global objects, tool modules

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.