検索

Egg.jsノードですか?

Dec 29, 2022 pm 02:51 PM
nodeegg.js

egg.js は、Koa から継承されたノード フレームワークです。egg.js フレームワークは、exporess や koa などの基本的なフレームワークとは異なります。アプリケーション レベルでビジネス シナリオに近づけ、より迅速に開始できるようにします。

Egg.jsノードですか?

#このチュートリアルの動作環境: Windows 10 システム、egg.js v2.0.0 バージョン、Dell G3 コンピューター。

egg.js ノードですか? #########はい。

egg.js を理解する

Egg は、Koa から継承された Node.js フレームワークです。 expoless や koa などの基本的なフレームワークとは異なり、egg.js はアプリケーション レベルで洗練されてカプセル化されているため、ビジネス シナリオに近くなり、より迅速に開始できるようになります。

Egg は、「設定よりも規約の方が優れている」という規約に従って開発されており、チームの共同作業のコストは低くなります

インストール

npm init egg
npm i
npm run dev
基本的な API は大きく分けてルーティング、リクエストパラメータの取得、論理処理、レスポンスデータの返却で構成されます

Routing

app/router.js URL ルーティング ルールを構成するために使用されます

router.get("/", controller.home.index);
// 当访问GET '/' ,app/controller/home.js 下的 index 方法会执行
router.post("/create", controller.user.create);
// 当访问POST '/create' ,app/controller/user.js 下的 create 方法会执行

リクエスト パラメーターの取得

This.ctx.query は URL 内の次のパラメーターを取得します?

// GET /posts?category=egg&language=node
// app/controller/post.js
class PostController extends Controller {
  async listPosts() {
    const query = this.ctx.query;
    // {
    //   category: 'egg',
    //   language: 'node',
    // }
  }
}

this .ctx.params ルート内の動的パラメータを取得します

// app.get('/projects/:projectId/app/:appId', controller.app.listApp);
// GET /projects/1/app/2
class AppController extends Controller {
  async listApp() {
    const params = this.ctx.params;
    // {
    //   projectId: '1',
    //   appId: '2'
    // }
  }
}

this.ctx.request.body 本体パラメータを取得します

// POST /api/posts HTTP/1.1
// Host: localhost:3000
// Content-Type: application/json; charset=UTF-8
//
// {"title": "controller", "content": "what is controller"}
class PostController extends Controller {
  async listPosts() {
    const body = this.ctx.request.body;
    // {
    //   title: 'controller',
    //   content: 'what is controller'
    // }
  }
}

応答データを返します

this.ctx.body応答データを返す

class ViewController extends Controller {
  async show() {
    // 返回Content-Type为application/json的body
    this.ctx.body = {
      name: "egg",
      category: "framework",
      language: "Node.js",
    };
  }
  async page() {
    // 返回Content-Type为text/html的body
    this.ctx.body = "<html><h1 id="Hello">Hello</h1></html>";
  }
}

mysqlデータベースを使用する

mysqlプラグインをインストールする

npm i egg-mysql

設定

// config/plugin.js
exports.mysql = {
  enable: true,
  package: "egg-mysql",
};
// config/config.${env}.js
exports.mysql = {
  // 单数据库信息配置
  client: {
    // host
    host: "localhost",
    // 端口号
    port: "3306",
    // 用户名
    user: "root",
    // 密码
    password: "root",
    // 数据库名
    database: "database",
  },
};

使用する

// 查找id 为 ${uid}的用户
await this.app.mysql.get("users", { id: uid });

プロセス ビジネス ロジック

データベース操作を含むビジネス ロジックをアプリ/サービスに配置することをお勧めします

// app/service/user.js
const Service = require("egg").Service;
class UserService extends Service {
  async find(uid) {
    // 假如 我们拿到用户 id 从数据库获取用户详细信息
    const user = await this.app.mysql.get("users", { id: uid });
    return user;
  }
}
module.exports = UserService;

その後、データサービス層によって取得された情報は、コントローラーを通じて取得できます。

// app/controller/user.js
class UserController extends Controller {
  async info() {
    const ctx = this.ctx;
    const userId = ctx.params.id;
    // 调用service层的user下的find方法
    const user = await ctx.service.user.find(userId);
    ctx.body = user;
  }
}

基本的な CURD ステートメントでは、create、get、select、update、delete メソッドを使用できます

SQL ステートメントを直接実行するには、クエリ メソッドを使用できます

トランザクション コントロール

egg.js 官网:https://www.eggjs.org/zh-CN/

推奨学習: 「

node.js ビデオ チュートリアル

以上がEgg.jsノードですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
USESTATEの理解():React React Neact State Managementの包括的なガイドUSESTATEの理解():React React Neact State Managementの包括的なガイドApr 25, 2025 am 12:21 AM

usestate()isareacthookusedtomeStateinfunctionalComponents.1)itInitializeSandUpDatestate、2)colledatttheToplevelofComponents、3)canleadto'stalestate'ifnotusedly、and4)cancancancancancanbeoptimizeduptimizeduptimizedususecall -calleSuperesteSteSteSteSteSteSteSteSteStateSupteStateSuptateSuptatedates

Reactを使用することの利点は何ですか?Reactを使用することの利点は何ですか?Apr 25, 2025 am 12:16 AM

ReactisPopularduetoitsComponent Architecture、Virtualdom、Richecosystem、およびdeclarativenature.1)コンポーネントベースのarchitectureallowsforReusable anduipieces、改善様式および測定可能性。

Reactでのデバッグ:一般的な問題の特定と解決Reactでのデバッグ:一般的な問題の特定と解決Apr 25, 2025 am 12:09 AM

debugReactapplicationivivivity、EtheseStrategies:1)AddressPropdrillingWithContextapiorredux.2)HandLeasynchronousoperations withuthutateanduseeffect、Abortcontrollertopreventraceconditions.3)最適化合物を使用して、最適化合物を使用してください

ReactのUseState()とは何ですか?ReactのUseState()とは何ですか?Apr 25, 2025 am 12:08 AM

UseState()inReactallowsstateManagementInFunctionalComponents.1)itsimplifiesstateManagement、makeCodemoreconcise.2)usetheprevcountFunctionToupDateStateBasedTateBasedTateBadeStateValue、AvolidingStalestateSues.3)

useState()vs。usereducer():州のニーズに合った適切なフックを選択するuseState()vs。usereducer():州のニーズに合った適切なフックを選択するApr 24, 2025 pm 05:13 PM

ChooseuseState()forsimple,independentstatevariables;useuseReducer()forcomplexstatelogicorwhenstatedependsonpreviousstate.1)useState()isidealforsimpleupdatesliketogglingabooleanorupdatingacounter.2)useReducer()isbetterformanagingmultiplesub-valuesorac

UseState()を使用して状態を管理する:実用的なチュートリアルUseState()を使用して状態を管理する:実用的なチュートリアルApr 24, 2025 pm 05:05 PM

UseStateは、州の管理を簡素化し、コードをより明確にし、読みやすくし、Reactの宣言的な性質と一致するため、クラスコンポーネントやその他の州管理ソリューションよりも優れています。 1)UseStateを使用すると、状態変数を関数コンポーネントに直接宣言することができます。2)フックメカニズムの再レンダリング中に状態を覚えています。

UseState()を使用する時期と、代替の州管理ソリューションを検討するタイミングUseState()を使用する時期と、代替の州管理ソリューションを検討するタイミングApr 24, 2025 pm 04:49 PM

useUsestate()forlocalcomponentStatemanagement; compleartinative forglogic、orperformanceissues.1)useidealforsimple、localstate.2)useglobalStateSolutionSolutionSuxorContextForSharedState.3)OptForreDuxtormobxobxobxobforexSt

Reactの再利用可能なコンポーネント:コードの維持可能性と効率の向上Reactの再利用可能なコンポーネント:コードの維持可能性と効率の向上Apr 24, 2025 pm 04:45 PM

再利用することは、codecodemaintainabilityを抑制することを再生します

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター