In-depth understanding of the node. js http module, and in-depth understanding of node. js

Source: Internet
Author: User

In-depth understanding of the node. js http module, and in-depth understanding of node. js

The http module is mainly used to build an HTTP server and client. The HTTP module must be called to use the http server or client functions.

Create a server

Var http = require ("http"); var url = require ("url"); // create a server // http inherits from tcpvar server = http. createServer (function (req, res) {var urlstr = req. url; // obtain the Request Path var urlMethod = req. method; // obtain the Request method var urlObj = url. parse (urlstr, true); console. log (urlObj); console. log (urlMethod); res. end ("hello") ;}); server. listen (0, 8080 );

Process requests

There are two types of requests: get and post. The get request url address carries parameters, and req. url can get parameters, while post requests are more complex. Use req. on () to process post requests.

Post Request Method: Use req. on ("data" function () {}), concatenate the str string in req. on ("end", function () {}) Output str after reading is the parameter sent by the post request we want;

Get Request Method: Use url. parse (req. url, true). query on the request address to obtain the parameter.

Var http = require ("http"); var fs = require ("fs"); var url = require ("url"); var querystring = require ("querystring "); var server = http. createServer (function (req, res) {console. log (req. method); var pathname = url. parse (req. url, true ). pathname; if (pathname = "/") {// load the registration page var rs = fs. createReadStream ("post.html"); rs. pipe (res);} else if (pathname = "/post") {// process the post request var str = ""; req. on ("data", func Tion (chunk) {// console. log (chunk. toString (); str + = chunk;}); req. on ("end", function () {var postObj = querystring. parse (str); console. log (postObj) ;}} else if (pathname = "/get") {// get request var getObj = url. parse (req. url, true ). query; res. write (JSON. stringify (getObj); res. end ();} else if (pathname! = "/Favicon. ico ") {var rs = fs. createReadStream (". "+ pathname); rs. pipe (res) ;};}); server. listen (0, 8787 );

Process uploaded files

The front-end html code is as follows.

<Form action = "/upimg" method = "post" enctype = "multipart/form-data"> Username: <input type = "text" name = "user"> <br> password: <input type = "password" name = "pass"> <br> upload image: <input type = "file" name = "file1"> <br> <input type = "submit" value = "submit"> </form>

To upload a file, you must introduce the formidable module var formidable = require ("formidable"). If this module is not available, enter npm install formidable on the terminal for installation.

Form. parse (req, function (err, fields, fies) {}) three parameters of the callback function

  1. Err: error message returned
  2. Fields: the fields returned by the post request and their corresponding values.
  3. Fies: the object to be uploaded. The object contains many details about the object.

After obtaining the file information, read and write the copied file using the data stream.

Var http = require ("http"); var fs = require ("fs"); var url = require ("url "); // File Upload var formidable = require ("formidable"); var server = http. createServer (function (req, res) {var pathname = url. parse (req. url, true ). pathname; if (pathname = "/") {var rs = fs. createReadStream ("uploads.html"); rs. pipe (res);} else if (pathname = "/uploads") {// instantiate a formidable class var form = new formidable. incomingForm (); // call the par Se method form. parse (req, function (err, fields, files) {if (err) {return console. log (err);} else {// console. log ("field", fields); // store the field var fieldStr = JSON. stringify (fields); fs. writeFileSync ("1.txt", fieldStr); // Save the object if (! Fs. existsSync ("uploads") {fs. mkdir ("uploads");} // random path var filePath = files. img. path; var rs = fs. createReadStream (filePath); var ws = fs. createWriteStream (". /uploads/"+ files. img. name); rs. pipe (ws); rs. on ("data", function (chunk) {}) rs. on ("end", function () {console. log ("copied"); res. write ("uploaded"); res. end () ;}) res. setHeader ("Content-type", "text/html; charset = utf8"); console. log ("file", files );}})} Else if (pathname! = "/Favicon. ico ") {var rs = fs. createReadStream (". "+ pathname); rs. pipe (res) ;}}); server. listen (0, 8880 );

Http simulated Client

The most basic parameters are the following code blocks.

  1. Method: Specifies the request method;
  2. Host: the Server ip address. The local localhost is used as an example;
  3. Port: the port number of the server;
  4. Path: Request path;

In this case, http. createServer () is not used to create a server, but http. request () is used to request the server. The rest are similar to the server.

// Simulate the client var http = require ("http") through nodejs; var options = {method: "post", host: "localhost", port: 2121, path: "/"}; var request = http. request (options, function (res) {var str = ""; res. on ("data", function (chunk) {str + = chunk;}); res. on ("end", function () {console. log (str) ;})}); var obj = {name: "Li Si", age: 20} request. write (JSON. stringify (obj); request. end ();

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.