Nodejs での http モジュールとエクスポート共有の簡単な分析

青灯夜游
リリース: 2022-11-10 20:46:22
転載
1241 人が閲覧しました

この記事では、node の基本、http モジュールと module.exports エクスポート共有の理解と事例について説明します。皆さんのお役に立てれば幸いです。

Nodejs での http モジュールとエクスポート共有の簡単な分析

1. http モジュール

http モジュールは、Web サーバーを作成するために Node.js によって公式に提供されるモジュールです。 [関連チュートリアルの推奨事項: nodejs ビデオ チュートリアル ]

http モジュールによって提供される http.createServer() メソッドを使用すると、通常のコンピュータを Web サーバーに簡単に変えることができ、それによって Web を提供できます。外部世界へのリソース サービス。

1. Web サーバーの作成

  • http モジュールのインポート
  • Web サーバー インスタンスの作成
  • バインドサーバー インスタンスのリクエスト イベント、クライアントのリクエストをリッスンします。
  • サーバーを開始します。

#例: 8080 サービスをリッスンします。#

// 导入 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')
})
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

2. req request objectサーバーはクライアントのリクエストを受信する限り、サーバーを介してサーバーにバインドされたリクエストイベント処理関数を呼び出します。 on()

例: イベント処理関数で、クライアントに関連するデータまたは属性にアクセスします。

// 导入 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')
})
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

3. res 応答オブジェクト サーバーのリクエスト イベント処理関数で、サーバー関連のデータまたはプロパティにアクセスする場合は、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')
})
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

Nodejs での http モジュールとエクスポート共有の簡単な分析

4. 中国語文字化け問題を解決res.end()メソッド呼び出し時、クライアントに報告 中国語コンテンツを送信すると文字化けが発生するため、コンテンツのエンコード形式を手動で設定する必要がある

例: 中国語を解決する文字化け

// 导入 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')
})
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

Nodejs での http モジュールとエクスポート共有の簡単な分析

5. 異なる URL に応じて異なる HTML コンテンツに応答する

#例: 手順は次のとおりです

要求された URL アドレスを取得します
    #デフォルトの応答内容を 404 Not found に設定します
  • ユーザーが / または /index.html ホーム ページを要求したかどうかを決定します
  • ユーザーが要求したかどうかを決定します/about.html About page
  • に Content-Type 応答ヘッダーを設定して中国語を防止するかどうかを決定します文字化け
  • res.end()を使用してコンテンツをクライアントに応答します
  • // 导入 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 = &#39;<h1>404 Not Found!</h1>&#39;
        // 用户请求页是首页
        if(url === &#39;/&#39; || url === &#39;/index.html&#39;) {
            content = &#39;<h1>首页</h1>&#39;
        } else if (url === &#39;/about.html&#39;) {
            content = &#39;<h1>关于页面</h1>&#39;
        }
        // 设置 Content-Type 响应头 防止中文乱码
        res.setHeader(&#39;Content-Type&#39;, &#39;text/html; charset=utf-8&#39;)
        // 调用 res.end() 方法 向客户端响应一些内容
        res.end(content)
    })
    // 启动服务
    server.listen(8080, function () {
        console.log(&#39;http://127.0.0.1:8080&#39;)
    })
    ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析
Nodejs での http モジュールとエクスポート共有の簡単な分析
Nodejs での http モジュールとエクスポート共有の簡単な分析
Nodejs での http モジュールとエクスポート共有の簡単な分析
Nodejs での http モジュールとエクスポート共有の簡単な分析## 2. Node.js におけるモジュールの分類

#1. 3 つの主要なモジュール カテゴリ

組み込みモジュール: fs、path、http など、node.js によって正式に提供されます。

カスタム モジュール: ユーザーが作成したすべての .js ファイルはカスタム モジュールです
  • サードパーティ モジュール: サードパーティによって開発されたモジュールであり、使用する前にダウンロードする必要があります
  • 2. モジュールの範囲

問題を防止しますグローバル変数の汚染度 #例:

index.js ファイル

const username = &#39;张三&#39;

function say() {
    console.log(username);
}
ログイン後にコピー

test.js ファイル

const custom = require(&#39;./index&#39;)

console.log(custom)
ログイン後にコピー

##3. module.exports オブジェクトNodejs での http モジュールとエクスポート共有の簡単な分析

カスタム モジュールでは、 module.exports オブジェクトを使用して

モジュール内のメンバーを共有できます。 外部使用用。

外部 require() メソッドがカスタム モジュールをインポートすると、取得されるのは module.exports が指すオブジェクトです。

例:

index.jsファイル

const blog = &#39;前端杂货铺&#39;

// 向 module.exports 对象上挂载属性
module.exports.username = &#39;李四&#39;
// 向 module.exports 对象上挂载方法
module.exports.sayHello = function () {
    console.log(&#39;Hello!&#39;)
}
module.exports.blog = blog
ログイン後にコピー

test.js ファイル##

const m = require(&#39;./index&#39;)

console.log(m)
ログイン後にコピー

#

4、共享成员时的注意点

使用 require() 方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准

示例:

index.js 文件

module.exports.username = &#39;李四&#39;

module.exports.sayHello = function () {
    console.log(&#39;Hello!&#39;)
}

// 让 module.exports 指向一个新对象
module.exports = {
    nickname: &#39;张三&#39;,
    sayHi() {
        console.log(&#39;Hi!&#39;)
    }
}
ログイン後にコピー

test.js 文件

const m = require(&#39;./index&#39;)

console.log(m)
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

5、exports 和 module.exports

默认情况下,exports 和 module.exports 指向同一个对象

最终共享的结果,还是以 module.exports 指向的对象为准。

示例:

index1.js 文件

exports.username = &#39;杂货铺&#39;

module.exports = {
    name: &#39;前端杂货铺&#39;,
    age: 21
}
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

index2.js 文件

module.exports.username = &#39;zs&#39;

exports = {
    gender: &#39;男&#39;,
    age: 22
}
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

index3.js 文件

exports.username = &#39;杂货铺&#39;

module.exports.age = 21
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

index4.js 文件

exports = {
    gender: &#39;男&#39;,
    age: 21
}

module.exports = exports

module.exports.username = &#39;zs&#39;
ログイン後にコピー

Nodejs での http モジュールとエクスポート共有の簡単な分析

对 index2.js 文件结果的解析如下:

Nodejs での http モジュールとエクスポート共有の簡単な分析
对 index4.js 文件结果的解析如下:
Nodejs での http モジュールとエクスポート共有の簡単な分析
注意:为防止混乱,尽量不要在同一个模块中同时使用 exports 和 module.exports

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

以上がNodejs での http モジュールとエクスポート共有の簡単な分析の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:csdn.net
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!