Hand in hand to build the front-end development framework

Quickly build front-end and back-end development frameworks

insert image description here

New to Jianghu, please give me advice

Let's talk first, what pitfalls will Xiaobai encounter in the front-end and back-end development process? In the front-end and back-end development process, the front-end is mainly web design and data rendering, the front-end is always a pain, where is the main pain?

  • Pain in package management,

    Anyone who has developed the front-end knows that when installing project dependencies through npm, some package versions will conflict. For example, if your v-charts version is too high, it will cause vue and vue-router in the project to fail.

  • Pain in UI design

    People who don't have a sense of beauty can't do this job well. I still remember when I was a freshman, after learning HTML, CSS, and JavaScript, there were basically three parts in the design of the page, the header, the content area, and the footer. Not to mention the simplicity of the page, there was very little information presented to the user. . At this time, use other people's pages to strip out some unused modules. The idea is very good, but it is difficult to implement. If you move one part, you will hurt your whole body. The page is either a bug or the page style is invalid. Later, you can use the browser element positioning to accurately Strip the module, and this is a relatively good page.

  • There are many things to learn in pain.
    This point, the friends who study the front end should have a deep understanding. As the saying goes, there is no best framework, only the most suitable application scenario.

Let’s talk about the backend. With the continuous improvement of the spring ecology and the development of various persistence layer frameworks, the realization of the interface is quite easy. However, with the increase of website requirements and users, the website architecture will continue to be upgraded. From the previous vertical The application architecture transitions to a distributed service architecture, and even to a mobile computing architecture. These architectures are definitely inseparable from technical support, so Spring Security and Spring Cloud are the focus and difficulty of learning.

Front-end development process

The following content takes: vue+axios+elementUI+vcharts technology stack as an example

Preliminary knowledge

Note: In the vue project, in many cases, the npm method is used to add packages. It is recommended not to use npm install during development to install dependencies globally. What packages are needed and what to install, otherwise, use npm install to install globally, you don’t know how many packages will be downloaded, I remember deleting the node_module folder once, which contained 2000+ files, and it took nearly 10 minutes to delete, so It is recommended not to use npm install to install globally.

Build the vue environment

Prerequisite: The node environment has been installed

Related commands:

node -v  检查node版本
npm  -v  检查npm版本npm 
install -g cnpm --registry=https://registry.npm.taobao.org  换源加速插件下载
cnpm install vue  下载vue
vue -V  检查vue版本
vue init webpack fileName  通过vue指令初始化文件
.....
cnpm run dev                  启动服务
Ctrl+C                        关掉服务器

Understand the directory structure

The calling sequence after the vue project starts:

index.html---->main.js----->app.vue->index.js----->components/components

Description of project directory structure:

Table of contents illustrate
build The basic configuration of webpack, webpack.base.conf.js (you can look at the code)
config Build configuration directory, port number for project startup...
node_modules Toolkits that depend on node, and node install xxx are here
src Project core package
index.html entry page
package.json Project download package information, version...

The core package of the src project, improve the directory according to your own situation:

Table of contents illustrate
api All requests for the project
asserts Static resources, css, js, img...
pages page
components public component directory
router front-end routing
app.vue root component
main.js Entry js file

axios request processing

Create the src/api/http.js file (optional, create according to your own situation)

  • Set the corresponding parameters of the request
import axios from 'axios';
axios.defaults.timeout=6000;//设置超时时间6s
axios.defaults.retry = 4;//请求次数
axios.defaults.retryDelay = 1000;//间隙
axios.defaults.withCredentials=true;//允许跨域
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=utf-8';
axios.defaults.baseURL = 'http://localhost:8888';//基础url,后端地址
  • Set response interceptor
//响应拦截器
axios.interceptors.response.use(
    response=>{
    
      return response;},
    error => {
    
      return Promise.reject(error);}
);
  • Encapsulate get and post methods

Purpose: The post and get methods are used a lot later, and can be encapsulated, and then it can be called directly by passing parameters, reducing the amount of code on the page.

export function get(url, params = {
     
     }) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.get(url, {
    
    
      params: params
    })
      .then(response => {
    
    
        resolve(response.data);
      })
      .catch(err => {
    
    
        reject(err)
      })
  })
}
export function post(url, data = {
     
     }) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.post(url, data)
      .then(response => {
    
    
        resolve(response.data);
      }, err => {
    
    
        reject(err);
      })
  })
}

Page development and route mapping

Vue + Vue Router simplifies page development. Through Vue.js, components integrate pages, add Vue Router, map components to routes, and let Vue Router know where to render them.

Backend development process

Prerequisite: The database is ready

Take the springboot+mybatisplus technology stack as an example:

Preliminary knowledge:

springboot reference documentation: https://docs.spring.io/

mybatisplus reference documentation: https://mp.baomidou.com/guide/


Create a springboot project

It is recommended to use IDEA's Spring Initializr bootloader to create, one word: fast! ! !

Import related jar packages

You can search through the maven warehouse, official website: https://mvnrepository.com

Take the most basic example

<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
</dependency>
<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.16</version>
</dependency>
<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.2.6</version>
</dependency>
<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3.1</version>
</dependency>

Create application.yml, project basic configuration

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/xxx?userUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
  jackson:
    date-format: yyyy-MM-dd
    time-zone: GMT+8
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 20MB

server:
  port: 8888

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true

AutoGenerator generates project modules (optional, self-created)

Premise: import mybatis-plus-generator, spring-boot-starter-freemarker dependencies

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.5.3</version>
</dependency>

Reference code: https://mp.baomidou.com/guide/generator.html

Result: Entity, Mapper, Mapper XML, Service, Controller and other modules are generated.

Note: You can check each generated file, especially the time field. AutoGenerator will automatically generate the LocalTime type, and generally need to be changed to the Date type.

Create a configuration class

Purpose: To solve cross-domain problems, static resource mapping problems, etc. (change according to your own needs). So what is cross-domain? To put it simply, since the front-end and back-end ports are different, the front-end and back-end data transmission is solved through cross-domain.

Case code:

@Configuration
public class ApplicationConfig implements WebMvcConfigurer {
    
    
    //1.解决跨域问题:放行哪些路径、原始域、请求方法、是否验证
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
    //2.处理静态资源映射问题,定位各种文件或图像地址
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        //path=file:xxx(根目录)/img/singerPic/
        String path1="file:"+System.getProperty("user.dir")+System.getProperty("file.separator")
                + "img"+System.getProperty("file.separator")
                +"singerPic"+System.getProperty("file.separator");//歌手图像地址
        registry.addResourceHandler("/img/singerPic/**")
                .addResourceLocations(path1);
    }
}

Write the controller layer (core code)

Respond to JSON data for the front end according to the request initiated by the front end.

  • Service CRUD interface: get query single row, remove delete, list query collection, etc.

  • Generic T is any entity object

  • The object Wrapper is a conditional constructor, which can be null and can be queried unconditionally.

  • Conditional constructor wrapper, suitable for complex SQL, supports chaining.

    Reference document: https://mp.baomidou.com/guide/wrapper.html#alleq

    function illustrate example
    eq、no = 、 != eq("name", "老王")—>name = '老王'
    It 、Ie < 、 <= lt(“age”, 18)--->age < 18
    gt、ge > 、 >= ge("age", 18)—>age >= 18
    like、notLike LIKE '%value%' like(“name”, “王”)--->name like ‘%王%’
    isNotNull Field IS NULL isNotNull(“name”)--->name is not null
    between BETWEEN value 1 AND value 2 between(“age”, 18, 30)--->age between 18 and 30
    orderByDesc descending order orderByDesc(“score”)--->order by Score DESC

    Note: The first field of the parameter corresponds to the database property field

    Sample code:

    //名字、邮箱不为空且年龄为大于12
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.isNotNull("name")
           .isNotNull("email")
           .ge("age",12);
    

    Recommendation: Some students feel that using functions to operate the database may be confusing. You can configure the log in application.yml. When the method completes a call, the running window will print the log, and you can use the log to understand the underlying implementation.

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    

Summarize

At this point, the front-end and back-end frameworks are all set up. Afterwards, write the code according to the requirements. The front-end initiates a get or post request to the back-end through axios, and the back-end responds to the JSON data to the front-end. The front-end obtains the JSON data through vue syntax , render the data to the page, and the front-end and back-end functions of such an interface are completed.


The ability is limited, the article is insufficient, I hope you leave your footprints, and I will correct it as soon as possible...

Guess you like

Origin blog.csdn.net/weixin_44490884/article/details/119787875