search
HomeWeb Front-endFront-end Q&AWhat are the methods of nodejs http module

What are the methods of nodejs http module

Jan 25, 2022 pm 01:54 PM
http modulenodejs

The methods of the nodejs http module are: 1. createServer(), which can create a server instance; 2. listen(), which starts the server to listen to the specified port; 3. setHeader(); 4. write(); 5. end(); 6. get(); 7. request(), etc.

What are the methods of nodejs http module

The operating environment of this tutorial: 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 requests

  • headers: Headers of HTTP requests.

  • #url: The requested path.

1.2 Module methods

1.2.1 http module methods

createServer(callback) : Create a server instance.

1.2.2 Server instance methods

listen(port): Start the server to listen to the specified port.

1.2.3 HTTP response method

  • setHeader(key, value): Specify HTTP header information.

  • write(str): Specify the content of the HTTP response.

  • end(): Send HTTP response.

1.3 Processing GET requests

Http module is mainly used to build HTTP service. Building an HTTP server using Node.js is very simple.

var http = require('http');

http.createServer(function (request, response){
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');

    The first line of the above code
  • var http = require("http") means loading the http module
  • Then, calling the http module
  • createServer method, creates a server instance and assigns it to the variable http.
  • ceateServer methodaccepts a function as a parameter. The request parameter of the function is an object, representing the client's HTTP request.
  • The response parameter is also an Object representing the server-side HTTP response. The
  • response.writeHead method indicates that the server responds with an HTTP header; the response.end method indicates the specific content of the server's response, and closes the conversation after the response is completed.
  • The last
  • listen(8080) means to start the server instance and listen to the 8080 port of the local machine Save the above lines of code into a file app.js, and then use node to call this file, and the server will start running.
  • $ node app.js
At this time, the command line window will display a line of prompts

"Server running at port 8080.". Open the browser and visit http://localhost:8080. The web page displays "Hello world!". The above example is to generate a web page on the spot. You can also write the web page in advance, save it in a 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);
  });
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');

The following modifications are to display different content according to requests from different URLs, which is equivalent to making a prototype of a website.

var http = require("http");
http.createServer(function(req, res) {
  // 主页
  if (req.url == "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the homepage!");
  }
	// About页面
  else if (req.url == "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the about page!");
  }
  // 404错误
  else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 error! File not found.");
  }
}).listen(8080, "localhost");

The req (request) object of the callback function has the following attributes.

  • url: URL of the request
  • method: HTTP request method
  • headers: All HTTP header information of HTTP requests.

1.4 Processing POST requests

When the client uses the

POST method to send data, the server can process data and end two events, set up listening functions.

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();
  });

}).listen(8080);

dataThe event will be triggered every time a piece of data is received during the data receiving process, and the received data is passed into the callback function. The end event is triggered after all data reception is completed. By slightly modifying the above code, you can create the file upload function.

"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.length;
    var p = (uploadedBytes / fileSize) * 100;
    response.write("Uploading " + parseInt(p, 0) + " %\n");
  });

  request.on('end', function () {
    response.end("File Upload Complete");
  });
}).listen(3030, function () {
  console.log("server started");
});

2 Make a request

2.1 get()

##get method

Used to issue get requests. <pre class='brush:php;toolbar:false;'>function getTestPersonaLoginCredentials(callback) { return http.get({ host: &amp;#39;personatestuser.org&amp;#39;, path: &amp;#39;/email&amp;#39; }, function(response) { var body = &amp;#39;&amp;#39;; response.on(&amp;#39;data&amp;#39;, function(d) { body += d; }); response.on(&amp;#39;end&amp;#39;, function() { var parsed = JSON.parse(body); callback({ email: parsed.email, password: parsed.pass }); }); }); },</pre>

2.2 request()


request method

is used to issue HTTP request, its usage format as follows. <pre class='brush:php;toolbar:false;'>http.request(options[, callback])</pre>The options parameter of the request method can be an object or a string. If it is a string, it means that this is a URL, and Node will automatically call

url.parse()

internally to process this parameter. options object
can set the following properties<ul> <li> <code>host:HTTP请求所发往的域名或者IP地址,默认是localhost

  • hostname:该属性会被url.parse()解析,优先级高于host。
  • port:远程服务器的端口,默认是80。
  • localAddress:本地网络接口。
  • socketPath:Unix网络套接字,格式为host:port或者socketPath。
  • method:指定HTTP请求的方法,格式为字符串,默认为GET。
  • path:指定HTTP请求的路径,默认为根路径(/)。可以在这个属性里面,指定查询字符串,比如/index.html?page=12。如果这个属性里面包含非法字符(比如空格),就会抛出一个错误。
  • headers:一个对象,包含了HTTP请求的头信息。
  • auth:一个代表HTTP基本认证的字符串user:password。
  • agent:控制缓存行为,如果HTTP请求使用了agent,则HTTP请求默认为Connection: keep-alive,它的可能值如下:
    • undefined(默认):对当前host和port,使用全局Agent。
    • Agent:一个对象,会传入agent属性。
    • false:不缓存连接,默认HTTP请求为Connection: close。
  • keepAlive:一个布尔值,表示是否保留socket供未来其他请求使用,默认等于false。
  • keepAliveMsecs:一个整数,当使用KeepAlive的时候,设置多久发送一个TCP KeepAlive包,使得连接不要被关闭。默认等于1000,只有keepAlive设为true的时候,该设置才有意义。
    request方法的callback参数是可选的,在response事件发生时触发,而且只触发一次。
    http.request()返回一个http.ClientRequest类的实例。它是一个可写数据流,如果你想通过POST方法发送一个文件,可以将文件写入这个ClientRequest对象
    下面是发送POST请求的一个例子。
  • var postData = querystring.stringify({
      &#39;msg&#39; : &#39;Hello World!&#39;
    });
    
    var options = {
      hostname: &#39;www.google.com&#39;,
      port: 80,
      path: &#39;/upload&#39;,
      method: &#39;POST&#39;,
      headers: {
        &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,
        &#39;Content-Length&#39;: postData.length
      }
    };
    
    var req = http.request(options, function(res) {
      console.log(&#39;STATUS: &#39; + res.statusCode);
      console.log(&#39;HEADERS: &#39; + JSON.stringify(res.headers));
      res.setEncoding(&#39;utf8&#39;);
      res.on(&#39;data&#39;, function (chunk) {
        console.log(&#39;BODY: &#39; + chunk);
      });
    });
    
    req.on(&#39;error&#39;, function(e) {
      console.log(&#39;problem with request: &#39; + e.message);
    });
    
    // write data to request body
    req.write(postData);
    req.end();

    注意,上面代码中,req.end()必须被调用,即使没有在请求体内写入任何数据,也必须调用。因为这表示已经完成HTTP请求
    发送过程的任何错误(DNS错误、TCP错误、HTTP解析错误),都会在request对象上触发error事件

    3 搭建HTTPs服务器

    搭建HTTPs服务器需要有SSL证书。对于向公众提供服务的网站,SSL证书需要向证书颁发机构购买;对于自用的网站,可以自制。
    自制SSL证书需要OpenSSL,具体命令如下。

    openssl genrsa -out key.pem
    openssl req -new -key key.pem -out csr.pem
    openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
    rm csr.pem

    上面的命令生成两个文件:ert.pem(证书文件)key.pem(私钥文件)。有了这两个文件,就可以运行HTTPs服务器了。
    Node.js提供一个https模块,专门用于处理加密访问。

    var https = require(&#39;https&#39;);
    var fs = require(&#39;fs&#39;);
    var options = {
      key: fs.readFileSync(&#39;key.pem&#39;),
      cert: fs.readFileSync(&#39;cert.pem&#39;)
    };
    
    var a = https.createServer(options, function (req, res) {
      res.writeHead(200);
      res.end("hello world\n");
    }).listen(8000);

    上面代码显示,HTTPs服务器与HTTP服务器的最大区别,就是createServer方法多了一个options参数。运行以后,就可以测试是否能够正常访问。

    curl -k https://localhost:8000

    更多node相关知识,请访问:nodejs 教程

    The above is the detailed content of What are the methods of nodejs http module. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

    React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

    The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

    React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

    React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

    React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

    Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

    Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

    React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

    React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

    React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

    React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

    React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

    The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

    React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

    React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.