Server-side language comparison

advantage disadvantage
java Powerful function, ecological improvement, superior performance, suitable for large-scale application development The development efficiency is general, and the construction and deployment are tedious
php The best language in the world. Fast and efficient, economical company preferred Weak types, weak complex applications
node.js Good performance, easy to use The technological ecosystem is not perfect
Time to execute Fibonacci sequence (ms)
java 782
javascript 384
php 1222
python 3809
c# 3217
c++ 641
go 548

Introduction of nodejs

Node.js is simply JavaScript running on the server.

Node.js is an event-driven I/O server-side JavaScript environment based on Google’s V8 engine, which executes JavaScript very fast and performs very well.

The installation

Liverpoolfc.tv: nodejs. Cn /

The first application

const http = require("http");

http
  .createServer(function (request, response) {
    response.end("Hello World");
  })
  .listen(8080);
Copy the code

http://localhost:8080

egg.js

Egg is a Node.js framework inherited from Koa. Egg is developed by convention and follows a “convention over configuration” approach that reduces the cost of team collaboration

The installation

npm init egg
npm install
npm run dev
Copy the code

A basic API roughly consists of routing, retrieving request parameters, logical processing, and returning response data

routing

App /router.js is used to configure URL routing rules

router.get("/", controller.home.index);
// When accessing GET '/', the index method under app/controller/home.js is executed
router.post("/create", controller.user.create);
// When POST '/create' is called, the create method under app/controller/user.js executes
Copy the code

Get request parameters

This.ctx. query retrieves the URL? The following part of the argument

// 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',
    // }}}Copy the code

This.ctx. params gets the dynamic parameters in the route

// 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'
    // }}}Copy the code

This.ctx.request. body Gets the body argument

HTTP / 1.1 / / POST/API/posts
// 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'
    // }}}Copy the code

Return response data

This.ctx. body returns the response data

class ViewController extends Controller {
  async show() {
    // Return content-type application/json body
    this.ctx.body = {
      name: "egg".category: "framework".language: "Node.js"}; }async page() {
    // Return content-type text/ HTML body
    this.ctx.body = "<html><h1>Hello</h1></html>"; }}Copy the code

Connect to mysql database

  • Install mysql plug-in
npm i egg-mysql
Copy the code
  • configuration
// config/plugin.js
exports.mysql = {
  enable: true.package: "egg-mysql"};Copy the code
// config/config.${env}.js
exports.mysql = {
  // Configure single database information
  client: {
    // host
    host: "localhost"./ / the port number
    port: "3306"./ / user name
    user: "root"./ / password
    password: "root".// Database name
    database: "database",}};Copy the code
  • use
// find the user with id ${uid}
await this.app.mysql.get("users", { id: uid });
Copy the code

Process business logic

Business logic is recommended in app/ Service, including database operations

// app/service/user.js
const Service = require("egg").Service;

class UserService extends Service {
  async find(uid) {
    // Get user details from the database
    const user = await this.app.mysql.get("users", { id: uid });
    returnuser; }}module.exports = UserService;
Copy the code

You can then retrieve the data from the Service layer through the Controller.

// app/controller/user.js
class UserController extends Controller {
  async info() {
    const ctx = this.ctx;
    const userId = ctx.params.id;
    // Call the find method under user in the service layer
    const user = awaitctx.service.user.find(userId); ctx.body = user; }}Copy the code

Basic CURD statements can be executed directly using the CREATE, GET, SELECT, update, and delete methods. SQL statements can be executed using the Query method

other

Control of transactions

sequelize

Sequelize is a widely used ORM framework that supports multiple data sources such as MySQL, PostgreSQL, SQLite, and MSSQL.

helper

The Helper functions are used to provide utility functions.

// extend/helper.js
// The response was processed successfully
exports.success = ({ ctx, res = null, msg = 'Request successful' }) = > {
  ctx.body = {
    code: 0.data: res,
    msg
  }
  ctx.status = 200
}
Copy the code

Exception handling middleware

Ctx.throw (404, ‘this is error MSG ‘) throws exceptions that can be handled uniformly in middleware

module.exports = (option, app) = > {
  return async function (ctx, next) {
    try {
      await next()
    } catch (err) {
      // All exceptions raise an error event on the app, and the framework logs an error
      app.emit('error', err, this)
      const status = err.status || 500
      // The details of the 500 error in production are not returned to the client because they may contain sensitive information
      const error = status === 500 && app.config.env === 'prod' ?
        'Internal Server Error' :
        err.message
      // Read each property from the error object and set it into the response
      ctx.body = {
        code: status, // Server's own processing logic error (including frame error 500 and custom business logic error 533 start) client request parameter error (4xx start), set different status code
        error: error
      }
      if (status === 422) {
        ctx.body.detail = err.errors
      }
      ctx.status = 200}}}Copy the code

Eggjs is introduced here. Please visit the official website for detailed documentation

Refer to the link

An egg. Js’s official website

Best practices for RESTful apis based on egg.js

egg-jwt