This article talks about the basics of node, the understanding and cases of http module and module.exports export sharing, I hope it will be helpful to everyone!
1. http module
The http module is a module officially provided by Node.js for creating web servers. [Related tutorial recommendations: nodejs video tutorial]
Through the http.createServer() method provided by the http module, you can easily turn an ordinary computer into a web server , thereby providing web resource services to the outside world.
1. Create a web server
- Import the http module
- Create a web server instance
- Bind to the server instance request event, listen to the client's request
- Start the server
Example: Listen to the 8080 service
// 导入 http 模块 const http = require('http') // 创建 web 服务器实例 const server = http.createServer() // 为服务器实例绑定 request 事件 监听客户端的请求 server.on('request', function (req, res) { console.log('请求中...') }) // 启动服务 server.listen(8080, function () { console.log('http://127.0.0.1:8080') })
2. req request object
As long as the server receives the client's request, it will call the request event processing function bound to the server through server.on()
Example: In the event handling function, access data or attributes related to the client
// 导入 http 模块 const http = require('http') // 创建 web 服务器实例 const server = http.createServer() // req 是请求对象 包含了与客户端相关的数据和属性 server.on('request', (req) => { // req.url 客户端请求的 url 地址 const url = req.url // req.method 是客户端请求的 method 类型 const method = req.method const str = `Your request url is ${url} and request method is ${method}` console.log(str) }) // 启动服务 server.listen(8080, function () { console.log('http://127.0.0.1:8080') })
3. res response object
In the server's request event handling function, if you want to access server-related data or properties, you need to use response
Example: Request response
// 导入 http 模块 const http = require('http') // 创建 web 服务器实例 const server = http.createServer() // req 是请求对象 包含了与客户端相关的数据和属性 server.on('request', (req, res) => { // req.url 客户端请求的 url 地址 const url = req.url // req.method 是客户端请求的 method 类型 const method = req.method const str = `Your request url is ${url} and request method is ${method}` console.log(str) // 调用 res.end() 方法 向客户端响应一些内容 res.end(str) }) // 启动服务 server.listen(8080, function () { console.log('http://127.0.0.1:8080') })
4. Solve the problem of Chinese garbled characters
When calling the res.end() method, report to the client When sending Chinese content, garbled characters will occur, and you need to manually set the encoding format of the content
Example: Solve Chinese garbled characters
// 导入 http 模块 const http = require('http') // 创建 web 服务器实例 const server = http.createServer() // req 是请求对象 包含了与客户端相关的数据和属性 server.on('request', (req, res) => { // req.url 客户端请求的 url 地址 const url = req.url // req.method 是客户端请求的 method 类型 const method = req.method const str = `请求地址是 ${url} 请求方法是 ${method}` console.log(str) // 设置 Content-Type 响应头 解决中文乱码问题 res.setHeader('Content-Type', 'text/html; charset=utf-8') // 调用 res.end() 方法 向客户端响应一些内容 res.end(str) }) // 启动服务 server.listen(8080, function () { console.log('http://127.0.0.1:8080') })
5. Respond to different html content according to different URLs
Example: The steps are as follows
- Get the requested url address
- Set the default response content to 404 Not found
- Determine whether the user requested / or /index.html home page
- Determine whether the user requested Whether to set the Content-Type response header for /about.html About page
- to prevent Chinese garbled characters
- Use res.end() to respond the content to the client
// 导入 http 模块 const http = require('http') // 创建 web 服务器实例 const server = http.createServer() // req 是请求对象 包含了与客户端相关的数据和属性 server.on('request', (req, res) => { // req.url 客户端请求的 url 地址 const url = req.url // 设置默认的内容为 404 Not Found let content = '<h1 id="nbsp-Not-nbsp-Found">404 Not Found!</h1>' // 用户请求页是首页 if(url === '/' || url === '/index.html') { content = '<h1 id="首页">首页</h1>' } else if (url === '/about.html') { content = '<h1 id="关于页面">关于页面</h1>' } // 设置 Content-Type 响应头 防止中文乱码 res.setHeader('Content-Type', 'text/html; charset=utf-8') // 调用 res.end() 方法 向客户端响应一些内容 res.end(content) }) // 启动服务 server.listen(8080, function () { console.log('http://127.0.0.1:8080') })
## 2. Module classification in Node.js
1. Three major module categories
- Built-in modules: Officially provided by node.js, such as fs, path, http, etc.
- Custom module: Every .js file created by the user is a custom module
- Third-party module: A module developed by a third party, which must be downloaded before use
2. Module scope
Prevents the problem of global variable pollutionExample:index.js file
const username = '张三' function say() { console.log(username); }
test.js file
const custom = require('./index') console.log(custom)
##3. module.exports object In a custom module, you can use the module.exports object to
share members within the modulefor external use. When the external require() method imports a custom module, what is obtained is the object pointed to by module.exports
Example:
index.js fileconst blog = '前端杂货铺'
// 向 module.exports 对象上挂载属性
module.exports.username = '李四'
// 向 module.exports 对象上挂载方法
module.exports.sayHello = function () {
console.log('Hello!')
}
module.exports.blog = blog
const m = require('./index')
console.log(m)
4、共享成员时的注意点
使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准
示例:
index.js 文件
module.exports.username = '李四' module.exports.sayHello = function () { console.log('Hello!') } // 让 module.exports 指向一个新对象 module.exports = { nickname: '张三', sayHi() { console.log('Hi!') } }
test.js 文件
const m = require('./index') console.log(m)
5、exports 和 module.exports
默认情况下,exports 和 module.exports 指向同一个对象。
最终共享的结果,还是以 module.exports 指向的对象为准。
示例:
index1.js 文件
exports.username = '杂货铺' module.exports = { name: '前端杂货铺', age: 21 }
index2.js 文件
module.exports.username = 'zs' exports = { gender: '男', age: 22 }
index3.js 文件
exports.username = '杂货铺' module.exports.age = 21
index4.js 文件
exports = { gender: '男', age: 21 } module.exports = exports module.exports.username = 'zs'
对 index2.js 文件结果的解析如下:
对 index4.js 文件结果的解析如下:
注意:为防止混乱,尽量不要在同一个模块中同时使用 exports 和 module.exports
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of A brief analysis of the http module and export sharing in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function