In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "nodejs http module method how to use", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's train of thought slowly in depth, together to study and learn "nodejs http module method how to use" it!
The methods of nodejs http module are: 1, createServer (), can create server instance; 2, listen (), start the server to listen on the designated port; 3, setHeader (); 4, write (); 5, end (); 6, get (); 7, request (), etc.
This tutorial operating environment: windows7 system, nodejs version 12.19.0, DELL G3 computer.
Http module
1 basic usage
1.1 Module Properties
1.1.1 attributes of HTTP request
Header information requested by headers:HTTP.
Url: the path to the request.
1.2 Module method
1.2.1 method of http module
CreateServer (callback): create a server instance.
1.2.2 method of server instance
Listen (port): starts the server to listen on the specified port.
1.2.3 method of HTTP response
SetHeader (key, value): specify HTTP header information.
Write (str): specifies the content of the HTTP response.
End (): sends a HTTP response.
1.3 processing GET requests
The Http module is mainly used to build HTTP services. Using Node.js to build a HTTP server is very simple.
Var http = require ('http'); http.createServer (function (request, response) {response.writeHead (200,{' Content-Type': 'text/plain'}); response.end (' Hello World\ n');}) .birthday (8080, "127.0.0.1"); console.log ('Server running on port 80800.')
The first line of the code above, var http = require ("http"), indicates that the http module is loaded
Then, call the createServer method of the http module, create a server instance, and assign it to the variable http.
The ceateServer method takes a function as a parameter, whose request parameter is an object that represents the client's HTTP request
The response parameter is also an object that represents the server-side HTTP response. The response.writeHead method indicates that the server responds to a HTTP header message; the response.end method indicates the specific content of the server response and closes the conversation after the response is completed
The final listen (8080) starts the server instance and listens on port 8080 of the machine
Save the above lines of code as a file app.js, then call the file with node, and the server starts running.
$node app.js
The command line window displays the prompt "Server running at port 8080." Open a browser, visit http://localhost:8080, and the web page displays "Hello world!".
The above example is to generate a web page on the spot, or you can write the web page beforehand, store it in the file, and then use the fs module to read the web page file and return it.
Var http = require ('http'); var fs = require (' fs'); http.createServer (function (request, response) {fs.readFile ('data.txt', function readData (err, data) {response.writeHead (200,{' Content-Type': 'text/plain'}); response.end (data);}) .customers (8080, "127.0.0.1"); console.log (' Server running on port 80800.')
The following changes are based on different URL requests to display different content, which is tantamount to making a prototype of a website.
Var http = require ("http"); http.createServer (function (req, res) {/ / homepage if (req.url = = "/") {res.writeHead (200,{ "Content-Type": "text/html"}); res.end ("Welcome to the homepage!") } / / About page else if (req.url = "/ about") {res.writeHead (200,{ "Content-Type": "text/html"}); res.end ("Welcome to the about page!");} / / 404 error else {res.writeHead (404, {"Content-Type": "text/plain"}); res.end ("404 error! File not found. ");}}) .localhost (8080,")
The req (request) object of the callback function has the following properties.
Url: the URL from which the request was made
Method of method:HTTP request
All HTTP header information requested by headers:HTTP.
1.4 processing POST requests
When the client uses the POST method to send data, the server can set up listening functions for data and end events.
Var http = require ('http'); http.createServer (function (req, res) {var content = "; req.on (' data', function (chunk) {content + = chunk;}); req.on ('end', function () {res.writeHead (200, {" Content-Type ":" text/plain "}); res.write (" You've sent: "+ content); res.end ();}).
The data event is triggered every time a piece of data is received during the data reception process, and the received data is passed into the callback function. The end event is triggered after all data has been received.
With a little modification to the above code, you can make the function of file upload.
"use strict"; var http = require ('http'); var fs = require (' fs'); var destinationFile, fileSize, uploadedBytes;http.createServer (function (request, response) {response.writeHead (200); destinationFile = fs.createWriteStream ("destination.md"); request.pipe (destinationFile); fileSize = request.headers ['content-length']; uploadedBytes = 0; request.on (' data', function (d) {uploadedBytes + = d.folth; var p = (uploadedBytes / fileSize) * 100) Response.write ("Uploading" + parseInt (p, 0) + "%\ n");}); request.on ('end', function () {response.end ("File Upload Complete");});}) .console.log (3030, function () {console.log ("server started");})
2 make a request
2.1 get ()
The get method is used to issue a get request.
Function getTestPersonaLoginCredentials (callback) {return http.get ({host: 'personatestuser.org', path:' / email'}, function (response) {var body =''; response.on ('data', function (d) {body + = d;}); response.on (' end', function () {var parsed = JSON.parse (body)) Callback ({email: parsed.email, password: parsed.pass);}
2.2 request ()
The request method is used to issue a HTTP request, and it is used in the following format.
Http.request (options [, callback])
The options parameter of the request method can be either an object or a string. If it is a string, it means that this is a URL,Node, then url.parse () is automatically called inside to process this parameter.
The options object can set the following properties
The domain name or IP address to which the host:HTTP request is sent. Default is localhost.
Hostname: this attribute is parsed by url.parse () and takes precedence over host.
Port: the port of the remote server. The default is 80.
LocalAddress: local network interface.
SocketPath:Unix network socket in the format of host:port or socketPath.
Method: specifies the method of the HTTP request, formatted as a string, and defaults to GET.
Path: specifies the path of the HTTP request. The default is the root path (/). You can specify a query string, such as / index.html?page=12, in this property. If this property contains illegal characters (such as spaces), an error is thrown.
Headers: an object that contains the header information of the HTTP request.
Auth: a string user:password representing the basic authentication of HTTP.
Agent: controls caching behavior. If agent is used in the HTTP request, the HTTP request defaults to Connection: keep-alive, and its possible values are as follows:
Undefined (default): uses the global Agent for the current host and port.
Agent: an object that passes in the agent attribute.
False: connection is not cached. The default HTTP request is Connection: close.
KeepAlive: a Boolean value indicating whether to reserve socket for future requests, which is equal to false by default.
KeepAliveMsecs: an integer that, when using KeepAlive, sets how often a TCP KeepAlive packet is sent so that the connection is not closed. The default value is 1000, which is meaningful only if keepAlive is set to true.
The callback parameter of the request method is optional, triggered when the response event occurs, and only once.
Http.request () returns an instance of the http.ClientRequest class. It is a writable data stream, and if you want to send a file through the POST method, you can write the file to the ClientRequest object.
Here is an example of sending a POST request.
Var postData = querystring.stringify ({'msg':' Hello wordings'}); var options = {hostname: 'www.google.com', port: 80, path:' / upload', method: 'POST', headers: {' Content-Type': 'application/x-www-form-urlencoded',' Content-Length': postData.length}} Var req = http.request (options, function (res) {console.log ('STATUS:' + res.statusCode); console.log ('HEADERS:' + JSON.stringify (res.headers)); res.setEncoding ('utf8'); res.on (' data', function (chunk) {console.log ('BODY:' + chunk);}); req.on ('error', function (e) {console.log (' problem with request:'+ e.message) }); / / write data to request bodyreq.write (postData); req.end ()
Note that in the above code, req.end () must be called, even if no data is written into the request body. Because this means that the HTTP request has been completed.
Any error in the sending process (DNS error, TCP error, HTTP parsing error) triggers the error event on the request object.
3. Set up HTTPs server
SSL certificate is required to build a HTTPs server. For websites that provide services to the public, SSL certificates need to be purchased from certification authorities; for websites for their own use, they can be made by themselves.
OpenSSL is required for self-made SSL certificate. The specific commands are as follows.
Openssl genrsa-out key.pemopenssl req-new-key key.pem-out csr.pemopenssl x509-req-days 9999-in csr.pem-signkey key.pem-out cert.pemrm csr.pem
The above command generates two files: ert.pem (certificate file) and key.pem (private key file). With these two files, you can run the HTTPs server.
Node.js provides a https module designed to handle encrypted access.
Var https = require ('https'); var fs = require (' fs'); var options = {key: fs.readFileSync ('key.pem'), cert: fs.readFileSync (' cert.pem')}; var a = https.createServer (options, function (req, res) {res.writeHead (8000); res.end ("hello world\ n");}).
The above code shows that the biggest difference between the HTTPs server and the HTTP server is that the createServer method has an extra options parameter. After running, you can test whether it can be accessed properly.
Curl-k https://localhost:8000 thank you for reading, the above is "how to use the http module method of nodejs" content, after the study of this article, I believe you have a deeper understanding of how to use the http module method of nodejs, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.