This article mainly gives you a brief introduction to the http module and url module in node.js. The article introduces it in detail through sample code. It has certain reference learning value for everyone to learn or use node.js. Friends who need it Let's learn together with the editor, I hope it can help everyone.
Preface
This article mainly introduces to you the relevant content about the http module and url module in node.js, and shares it for your reference and study. I won’t say much more below. Let’s take a look at the detailed introduction.
1. A brief introduction to the http module
The http built-in module in node.js can be used to create http servers and http clients.
1. Introduction package
const http = require('http');
2. Create http server
var server = http.createServer((req,res)=>{ });
Using the .createServer() method of http can be used to return an http server instance, using a custom server variable to receive. When the server receives a request from a client, it triggers a call to its internal callback function. Every time the client accesses it, it triggers a call. The callback function has two parameters, req and res, the order cannot be reversed, req represents the request, and res represents the response.
The internal statement of the callback function must contain res.end();, because if not, the browser will think that it has not received a response from the server, and the browser will always be suspended. status, at this time there is a timeout mechanism inside the browser. Once it times out, an error will be reported.
Commonly used code statements in this callback function are:
Set the response header, res.writeHead(status code, {}); among them, the commonly used HTTP status codes are 200 (return successfully), 404 (the page cannot be found, error returned), etc. The second parameter is passed in an object, which is used to set the rendering parsing type of the response text. For example, the commonly used setting for html code is, res.writeHead(200,{"Content-Type":"text/html;charset=UTF8"});. The setting for css files is res.writeHead(200,{"Content-Type":"text/css"});. The setting for pictures is res.writeHead(200,{"Content-Type":"image/jpg"});. For plain text, the setting is res.writeHead(200,{"Content-Type":"text/plain"}); set the returned content, res.write('');
3. Let the The server listens to a specific port number
Use the custom variable server to represent the created server to listen to a specified port number. server.listen(3000,'192.168.155.1'); External clients can access this server through this IP address and port number.
At this time, it means that the server is in a suspended state. At this time, enter the corresponding IP address and port number in the browser to get the content of the server response.
2. A brief introduction to the url module
const http = require('http'); var server = http.createServer((req,res)=>{ console.log(req.url); res.end(); }); server.listen(3000,'192.168.155.1');
When you use the node command to open this server, you can print out the URL address of the accessed client in real time on the console. information.
Since when accessing through the chrome browser, each access will be accompanied by a request for /favicon.ico by default. When parsing the client, the browser actually When accessing the address, you can do the following processing:
const http = require('http'); var server = http.createServer((req,res)=>{ if(req.url == '/favicon.ico'){ return; }; console.log(req.url); res.end(); }); server.listen(3000,'192.168.155.1');
As shown in the figure above, we can get the user's complete request address through req.url. We can use The built-in url module parses the user's request address.
1. Introduction package
const url = require('url');
2. The commonly used method is url.parse(req.url)
This method is commonly used to decompose a complete url address into a object.
const http = require('http'); const url = require('url'); var server = http.createServer((req,res)=>{ if(req.url == '/favicon.ico'){ return; }; console.log(url.parse(req.url)); res.end(); }); server.listen(3000,'192.168.155.1');
The most commonly used one is url.parse(req.url).pathname to get a string of file path, starting with /, and not including the query part of the content. Use url.parse(req.url).query to get a query part of the string. The second parameter of the url.parse() method is true, which can convert all queries into object form.
console.log(url.parse(req.url,true).query);
In this way, the data submitted by the client to the server through GET can be quickly obtained.
Related recommendations:
Detailed explanation of HTTP module and event module in Node.js
NodeJS study notes Http module_node.js
golang uses http module to build redis read-write query api
The above is the detailed content of Introduction to http module and url module in node.js. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools
