Introduction to the

This tutorial is designed for beginners to learn how to implement server-side development using the Node EggJS framework and how to deal with problems encountered during development.

Each chapter of the tutorial will be attached to the demo(Git branch), you can pull the code to see.

The tutorial and demo will use the ALita framework based on UMI secondary encapsulation for page rendering, focusing on the Node server framework of EggJS.

Implement a list of users obtained through a GET request and detailed user information obtained through a POST request.

As an entry-level, we do not need to pay too much attention to the API, technical things suggested to master the usage, use more can slowly understand the meaning. All the guys who look at shit are thugs.

Now let’s create the egg framework.

I. EggJS framework construction and explanation

Eggjs website – quick start

Using the link above, we were able to quickly scaffold EggJS.

Create a new folder
mkdir eggDemo && cd eggDemo
# scaffolding command
npm init egg --type=simple

Enter project PKG information manually? project name egg ? project description ? project author ? cookie security keys 1620311360934_6251Enter the project to install dependencies
cd init
yarn
Copy the code

While the dependencies are being installed, open the package.json file and look at the script tags.

"scripts": {
    "start": "egg-scripts start --daemon --title=egg-server-egg"."stop": "egg-scripts stop --title=egg-server-egg"."dev": "egg-bin dev". },Copy the code
  • yarn run start: startingeggservice
  • yarn run stopStop:eggservice
  • yarn run dev: Starts the development mode and supports hot deployment

The yarn Run Dev scaffold has been written for us as a minimal demo. Implements one of the simplest interfaces.

Eggjs follows the principle of convention over configuration, which can be simply interpreted as doing whatever files and folders are named after (the description is not accurate, but it’s probably close to the point).

For a complete directory structure, please refer to the official website and take a look at the scaffolding for us to build several directories:

  • /config/config.default.js: Configuration file
  • /config/plugin.js: Configure plug-ins

  • /app/router.js: Used to configure the URL routing rule, that is, the address of each interface
  • /app/controller/**: parses user input and returns corresponding results after processing
  • /app/public/**: Used to place static resources

In a real project there would be hundreds or thousands of interfaces, and craming them all into app/router.js might not work well. It is generally divided into modules or background centers to achieve.

The demo we will implement has two pages, the user list page and the user details page. Let’s divide it by page and create two new files for routing.

module.exports = app= > {
  require('./router/list')(app);
  require('./router/detail')(app);
};
Copy the code

Finally, we quickly build a front-end Web framework.

Type The Web scaffold under the folder eggDemo
yarn create alita eggWeb

cd eggWeb
yarn
Copy the code

To initialize the framework, take a look at the /config/config.ts and/SRC /app.ts files in demo.

Feat -frame-building Branch of the frame

2. User list interface development (GET request)

egg

Each interface has a unique route (interface name),

So let’s write the route first:

/router/list.js

'use strict';

module.exports = app= > {
  const { router, controller } = app;
  router.get('/api/getUserList', controller.home.userList);
};
Copy the code
  • router.getStands for GET request.
  • controller.home.userListControllerRepresentative:controllerExists under folderhomeThe file. It’s in the fileuserListControllerMethods.

/app/controller/home.js

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async userListController() {
    const { ctx } = this;
    const data = Array.from(new Array(9)).map((_val, i) = > ({
      name: `name${i}`.id: i,
    }));
    ctx.body = {
      data,
      success: true}; }}module.exports = HomeController;
Copy the code
  • async: can be understood as a convention, representing asynchrony.

This parameter description:

parameter instructions
this.ctx An instance of the current request Context object, from which we can retrieve the convenient properties and methods encapsulated in the framework for handling the current request (better access to request Context data).
this.app The instance of the currently applied Application object, from which we can get global objects and methods provided by the framework
this.service Through it we can access the abstract business layer, equivalent tothis.ctx.service, service is used for the low-level encapsulation of the server
this.config Apply runtime configuration items

Finished the get request from the server, start the service, open the http://127.0.0.1:7001/api/getUserList, can see the request data is displayed on the screen.

web

Develop web side code, request/API /getUserList interface.

/ SRC/pages/index/service. The ts: use useRequest request parameters.

import { request } from 'alita';

export async function getUserList() :Promise<any> {
  return request('/api/getUserList', { method: 'get' });
}
Copy the code

/src/pages/index/index.tsx:

import React, { FC, Fragment } from 'react';
import { useRequest, history } from 'alita';
import { Button } from 'antd-mobile';
import { getUserList } from './service';
import styles from './index.less';

interface HomePageProps {}

const HomePage: FC<HomePageProps> = () = > {
  const { data, run } = useRequest(getUserList, {
    manual: true});return (
    <div className={styles.center}>
      {data && (
        <Fragment>
          <div>Call getUserList with:</div>
          {data.map((item: any) => (
            <div
              onClick={()= >{ history.push({ pathname: '/userDetail', query: { id: item.id, }, }); }} key={item? .id} style={{ height: '1rem', }} > {item.name}</div>
          ))}
        </Fragment>
      )}
      <Button onClick={()= >The run ()} > get request</Button>
    </div>
  );
};
export default HomePage;
Copy the code

Cross-domain problem

Start web project access: http://localhost:8000/#/ Click the button to call the interface and find that the data is Not displayed, interface status code 304 Not Modified.

A closer look at the interface shows that the service interface and Web are not the same, and there should be cross-domain problems. We need to add proxies to solve the cross-domain problems:

/config/config.js

import { defineConfig } from 'alita';

const baseUrl = 'http://127.0.0.1:7001';

export default defineConfig({
  appType: 'h5'.mobileLayout: true.proxy: {
    '/api': {
      target: baseUrl,
      changeOrigin: true,}}});Copy the code

At this point, a complete GET request interface is completed from development to Web side interface rendering.

Feat – user – branch of the list

The next article will take you to the EggJS Implementation server request tutorial document-2